Passing &mut to nested function

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();

fn main() {
    let mut s = String::new();
    let n = next_num(&mut s);
    println!("{}", n);


You just have to remote the &mut part in the first line of next_num.

As the .read_line( function takes an &mut String, and s has this specific type, you can just pass it directly:


Oh, got it, thanks a lot! So it is not about borrowing but I just was so silly to confuse types!

Works now, though it seems I need to add .clear() inside the method if I want to reuse the same string.

1 Like

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.

1 Like

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! :+1:

The clear method does not zero the string. Reusing the string is more efficient.


Sorry I just checked and indeed it does not rewrite the string, sorry for the mistake ^^'

Well, Friends, thanks for this yet further clarification :slight_smile:

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...

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.