Associated function `display` is never used

Viewed 49

There is a basic struct implementation that gives me this warning. I want to create methods on a struct. As far as I understand (please correct me if I am wrong), the difference between methods and associative functions is the &self parameter. But for some reason, rust is taking those as associative functions:

struct User {
    name: String,
    date: u64,
}
impl User {
    fn display(&self) {
        println!("{}", self.name);
    }
}

Here is the warning which I am getting:

associated function `display` is never usedrustc(dead_code)

enter image description here

According to this resource (https://doc.rust-lang.org/book/ch05-03-method-syntax.html), I think this is the correct way to write methods.

1 Answers

Methods are associated functions, they are associated to the Type. You can even say var.method() is just syntax sugar for Type::method(&var), as they do the exact same thing.

Also, while there's nothing wrong with your implementation, for common functions like display, it is more idiomatic to implement the Display trait.

struct User {
    name: String,
    date: u64,
}

use std::fmt::{Display, Formatter};
impl Display for User {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { 
        write!(f, "{}", self.name)
    }
}

Once this trait is implemented, you can print User like this, also you get to_string() for free

let user = User { /* init */ };
println!("{}", user);
let user_s: String = user.to_string();

If you want to know more about traits, checkout the trait section in the rust book

Related