Rust newb. Help with the borrow checker


#1

So I have this code.

use std::env::args;
fn main() { 
    let mut argv = args();
    let argc = argv.count();
     if argc != 2 {
        println!("To many or too few arguments.");
    }
    let file_name = argv.nth(1);
}

How do I get it so that argv is not borrowed by the time I do this

let file_name = argv.nth(1);

#2

Like this:

fn main() {
    let args: Vec<String> = std::env::args().collect();
     if args.len() != 1 {
        println!("To many or too few arguments.");
    }
    let file_name = &args[0];
}

#3

In your original example, argv is not borrowed, it is consumed. In Rust, std::env::args is an iterator over the arguments, so, when you do argv.count(), Rust will traverse the whole iterator, discarding the actual arguments and just counting their number.


#4

So does that mean when argv is consumed by argv.count() that it is deallocated at the end of the consumption?


#5

The iterator itself is indeed deallocated. If you look at the count signature, you’ll see that it consumes self (there is not &self). So, this means that if you do xs.count() then xs sort of goes out of scope immediately and the count becomes responsible for deallocating it.

But I don’t think that the arguments themselves are freed (and I am not sure if it is even possible, most likely no). So, if you call std::env::args() again you should get a fresh iterator.

Does this answers your question? :slight_smile:


#6

Yes it does. Thank you very much.