use std::io;
fn main() {
fn foo() -> &'static str {
println!("Your name...");
let mut name: String = String::new();
io::stdin()
.read_line(&mut name)
.expect("Something went wrong");
return name.trim_end();
}
println!("{}", foo());
}
Here's a fix with some brief comments.
- fn foo() -> &'static str {
+ // Return an owned value (`String`)
+ fn foo() -> String {
println!("Your name...");
let mut name: String = String::new();
io::stdin()
.read_line(&mut name)
.expect("Something went wrong");
- return name.trim_end();
+ // Trim the owned `String`
+ let len = name.trim_end().len();
+ name.truncate(len);
+ // The canonical way to return a value in Rust is to just have an
+ // expression with no `;` at the end
+ name
}
1 Like
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.