Let's create a sample test setup

The test code is very simple. We have a trait with a function that returns a String. We then have a couple of implementations and a parameter bound function that will display the result from the implementations:

trait StaticObject 
{
fn static_method(&self) -> String;
}

impl StaticObject for u8
{
fn static_method(&self) -> String {format!("u8 : {}, ", *self)}
}

impl StaticObject for String
{
fn static_method(&self) -> String {format!("string : {}", *self)}
}

fn display_code<T: StaticObject>(data : T)
{
println!("{}", data.static_method());
}

fn main()
{
let test_one = 8u8;
let test_two = "Some text".to_string();
display_code(test_one);
display_code(test_two);
}
The code for this part can be found in 09/trait_object_static.

When compiled and executed, we get the following:

From the previous explanation, we know that the compiler will generate the various types that T can be.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset