Generic types on functions outside of implementation blocks

It's possible to use generic type parameters for functions even when they're not part of an implementation block. That looks like this:

fn print_generic<T>(value: T) where T: Display {
println!("{}", value);
}

This function has a generic type parameter, T, which can be any data type that has the Display trait. That means that, if this function is defined, we can do things like this:

print_generic(12.7);
print_generic("Hello");
print_generic(75);

Each of those lines calls a different print_generic function, specialized for the data type of the parameter. The compiler generates code for each version of print_generic that we use, each one accepting a different data type for its parameter.

Of course, print_generic doesn't do anything that the plain println! macro doesn't, but it serves to demonstrate the ways of generic type parameters for standalone functions.
..................Content has been hidden....................

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