The emergence of conflicting borrowing scenarios in Rust

This first Rust program will not compile because it is b

discarded prior to its reference r

, which makes sense:

fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = &b;
    }
    println!("{}", v);
}

      

In this second Rust program, the reference to b

is fetched via a function, and suddenly there is no problem:

fn getRef(b: &str) -> &str {
    b
}

fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = getRef(&b);
    }
    println!("{}", v);
}

      

The point is that it v

is still a link to b

, but b

not available for println!()

.

Why are these two different?

+3


source to share


1 answer


Because they don't do the same.

If you print the type of the variable , you will see that in the first example v

has a type &&str

in particular & &'static str

, In the second example v

has a type &str

in particular &'static str

.

In the first example, you have a reference to a local value that is really out of scope.

In the second example, although you are taking a reference to b

when creating &&str

, you are calling the function expecting &str

. Deref

coercion
starts and automatically enacts the meaning.



So the second example is equivalent to

fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = b;
    }
    println!("{}", v);
}

      

That is, you make a copy of an immutable string reference that will live the entire life of the program.

+5


source







All Articles