0

[SOLVED] Return a value in function on rust

// the code below fn ask_name() -> &'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!("{}", ask_name());

16th Feb 2022, 6:43 AM
EsaKurniawan
7 odpowiedzi
+ 1
The lifetime of your str is not static. Return a String instead, passing ownership out. fn ask_name() -> String { // ... return name.trim_end().to_owned(); }
27th Feb 2022, 9:37 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Oh, all right :) What did they suggest?
27th Feb 2022, 10:06 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Right. Passing ownership out :)
27th Feb 2022, 10:16 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
😅
27th Feb 2022, 10:24 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
0
Actually already fixed it a long time ago, with help from rust community
27th Feb 2022, 9:42 AM
EsaKurniawan
0
They suggested something like this: fn foo() -> String { println!("Your name..."); let mut name: String = String::new(); io::stdin() .read_line(&mut name) .expect("Something went wrong"); // 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 }
27th Feb 2022, 10:11 AM
EsaKurniawan
0
Honestly i didn't understand that, but it's work🤣🤣
27th Feb 2022, 10:18 AM
EsaKurniawan