Hi !
Let’s create a generic log function. This will not make a lot of sense, since the println! function already support lots of data types. However, this is a nice way to understand how generics works.
Here is the log function.
use std::fmt::Display;
// Generic Function to print data to the console
fn console_log<T: Display>(x: T) {
println!("{}", x);
}
The log function receives a parameter x, that support any type from Display, and then it prints the parameter to the console.
The following sample shows
- Print a String
- Print an Integer
- Print a Struct, that implements a function to show the struct data
And the output is
Source Code
Super cool !
Happy coding!
Greetings
El Bruno
More posts in my blog ElBruno.com.