A generic problem

An aspect of generics is the determination of what T is and therefore how we can handle it. In C#, we can use System.Reflection and use the GetType method to find the type or use typeof when comparing types.

The source code for this part can be found in 09/generic_typeof.

In Rust, we use std::any:Any. This is a type to emulate dynamic typing:

Just by looking at this output, you may be thinking: What on earth are those numbers? I expected something like f32.

The associated code for this part can be found in 09/generic_typeof_print.

What we're seeing here is the ID for the type rather than the type. To actually show the variable type, we have do something slightly different:

#![feature(core_intrinsics)] 
fn display_type<T>(_: &T)
{
let typename = unsafe {std::intrinsics::type_name::<T>()};
println!("{}", typename);
}

fn main()
{
display_type(&3.14f32);
display_type(&1i32);
display_type(&1.555);
display_type(&(vec!(1,3,5)));
}
At the time of writing, this code will only build on the nightly branch. Chances are that by the time you read this book, it will be in the stable branch.

When the preceding code is run on the Rust Playground website, the following results are obtained:

While most of the code we have seen many times, we have not yet come across unsafe and the shebang (#!) in the code.

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

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