Hi Friends and sorry - most probably this was asked but I can't figure out suitable search keywords to filter out similar though different cases.
I create mutable string and pass it as &mut to function which should pass it the same way further. This fails with "cannot borrow as mutable" (most probably because I don't correctly understand that makes "simultaneous" borrowing). So what is the correct way (besides moving String::new into function itself)?
use std::io;
fn next_num(s: &mut String) -> i32 {
io::stdin().read_line(&mut s).unwrap();
s.trim().parse::<i32>().unwrap()
}
fn main() {
let mut s = String::new();
let n = next_num(&mut s);
println!("{}", n);
}
You'll be better off creating a new String each type, clearing an existing one takes time as it needs to be filled with zeroes, so it's not really efficient performance-wise.
Thanks for hint - didn't know it is filled with zeroes (rather than just length truncated) - will do accordingly! Creating new instances for any small object is something I get used to in java world, but was wondering if it is all right in rust. You clarified this point!
Well, Friends, thanks for this yet further clarification
I'll check out of curiosity whether efficiency is much improved by reusing the string - though probably for code cleanliness it's better to use new instances where possible. Most probably IO is not extremely efficient part of program...