How to trim whitespace of name?

fn main(){
  
  let person_one = Person{
    name:"Alice".to_string(), age:22
  };

  let data = person_one.summarize();
  println!("{:?}", data);


}

trait Summary{
    fn summarize(&self)-> String;
}

struct Person{
    name:String,
    age: u32
}

impl Summary for Person{
    fn summarize(&self)-> String {
        let name = self.name.trim();
        format!("My name is {:?} and age is {:?}", name,self.age)
    }
}

Now im getting printed as "My name is "Alice" and age is 22"

The way to trim whitespace is to use trim(), as you are doing (but you won't notice any difference since you aren't supplying an input string that has any whitespace).

The comment at the end of your post seems to be objecting to the inclusion of quotes in the output, but this has nothing to do with trimming whitespace. Rather, it is because you are using the Debug formatting (which for strings adds quotes). Debug is intended for debugging, not for user-facing output. You should use Display formatting instead, with the {} format specifier.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.