I am trying to write a method of an object that returns a combination of String fields of that object. I have tried several approaches, as you can see in the example code, and in each case I am getting errors shown below including
- expected
&str, found structstd::string::String sis borrowed here- cannot return value referencing local variable
s
struct Person {
first_name: String,
last_name: String,
age: u8,
}
// BEHAVIOR OF CLASS
impl Person {
fn full_name(&self) -> &str {
let s = format!("{} {}", self.first_name, self.last_name);
// temporary, test
println!("** test, s: {}", s);
// how to return the 's' value?
// try 1. expected `&str`, found struct `std::string::String`
// s
// try 2. `s` is borrowed here
// s.as_str()
// try 3. cannot return value referencing local variable `s`
// &s[..]
// try 4. cannot return value referencing local variable `s`
// &*s
// then escape
"?"
}
// works fine
fn description(&self) -> &str {
match self.age {
0..=12 => "Clild",
13..=17 => "Teenager",
_ => "Adult",
}
}
}
fn main() {
println!("Laboratory");
let p = Person {
first_name: String::from("Alexandra"),
last_name: String::from("Ansley"),
age: 25,
};
println!("Full Name : {}", p.full_name());
println!("Description : {}", p.description());
}
How can I write this method without these errors?
Stringobject, and try to return a reference to it. But, theStringobject will be destroyed immediately after the function ends. You better return the object itself, not a reference. ReturnStringtype, and return it as justs