How to display generic function?

I tried to show value of this generic function

   fn func<T>(x: T) {
    println!("{}", x);
}


fn main() {
    let p = "Hello".to_string();
    func(p);
}

but I got this error.

`T` doesn't implement `std::fmt::Display`

`T` cannot be formatted with the default formatter

help: the trait `std::fmt::Display` is not implemented for `T`
note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
help: consider adding a `where T: std::fmt::Display` bound
note: required by `std::fmt::Display::fmt`

I always getting this error whatever I do in Rust. How to fix this error ? What reason is getting this error ?
if I change this code to this:

   fn func(x: String) {
    println!("{}", x);
}


fn main() {
    let p = "Hello".to_string();
    func(p);
}

It's compiling and running without any problem. Maybe that's error has a really really basic solve but I'm new in Rust, sorry. Also, sorry for my bad english.

1 Like
use std::fmt::Display;

fn func<T: Display>(x: T) {
    println!("{}", x);
}

The T: Display says that T must implement the Display trait. You can then use it in main just like you did.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.