Code question (rustlings exercise)

Hi all -

I'm going to try to teach myself Rust (longtime C/C++ dinosaur). I'm going through some exercises provided by rustlings, and came across a curious line of code:

fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
    let mut vec = vec;
    ...
}

So, do I correctly read this that the function is declaring a local variable with the same name as the parameter? This example is from the move_semantics section, so it's possible that the author is trying to drive home a point here.

Oh, and this code isn't the problem...I already checked on that.

Thanks for any help...

Yes, the local variable is shadowing the parameter with the same name and the value is moved from the parameter into the local variable. This is equivalent to:

fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {

Thank you. I do remember reading about shadowing in the docs...it wasn't clear to me exactly what the value of it was, though. In this example, does shadowing gain me anything over the alternative you posted above? Because it does seem to cause ambiguity (I didn't post the entire function, for brevity.)

Thanks again..

The only reason for doing that that I can see is to hide the mut keyword in the body of the function instead of the header, so that it doesn't clutter the function header visually. I don't think it's worth it, personally.

The mut keyword in the function header doesn't actually affect what the API is, and the HTML documentation generated by rustdoc will skip it.

I imagine it's just to demonstrate how shadowing works, it's not something you'd write in actual code. The most common use for shadowing is probably when dealing with Options/Results or converting values, things like:

let some_number: Option<String> = maybe_read_string();
if let Some(some_number) = some_number { // some_number: String
    let some_number: i32 = some_number.parse();
    // do stuff with some_number
}

When working with Optionals in Java I would often name variables in cases like this someNumberOpt and such which always felt pretty redundant, so I'm glad to have shadowing in Rust.

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.