Is this a string literal?

fn main()
    let ani = vec!["Something", "ssdsads"];

    for a in ani
        println!("Val: {}", a);

    println!("{}", ani[0]); // Error over here since `a` has already taken ownership.

So inside the ani vector, am I using a string literal or a string? If I am using string literal, how come inside the for loop the a variable takes ownership of the contents inside ani if string literal's size is defined during compile time?

Because you are draining the ani Vec (taking ownership of it) in the for loop.
You can iterate over the Vec by using &ani without taking ownership of the Vec itself.

See the book, chapter 8 for more details.

A literal is a value that is literally written in the source code, like "Something" or 42. a is not a string literal, because it is an identifier.

Inside the for loop, a happens to represent a variable of type &'static str, which, in the first iteration of the loop, happens to be set to the value "Something". But it is not a string literal, it's always an identifier.

Okay, but &'static str is a Copy type, so your question is still valid: Why can't you use ani[0] after the loop, if it's not consumed by the println!? The answer is that the string itself is not consumed by the loop, but ani is, because it's a Vec<&'static str> and Vec is not Copy. After the loop, ani[0] doesn't exist anymore because ani has been moved out of.

If you want to avoid moving out of ani so that it can be used after the loop is over, you can iterate over it by reference as hellow mentioned.

1 Like

Oh i see,

So like even if I put numbers inside a Vector instead would still not be a copy, right?

Yes, because the Vec<T> contains heap memory allocation as a resource.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.