Codey
Codey

Reputation: 1233

Why use immutable Vector or String in Rust

I'm learning Rust and learned, that for making an expandable string or array, the String and Vec structs are used. And to modify a String or Vec, the corresponding variable needs to be annotated with mut.

let mut myString = String::from("Hello");
let mut myArray = vec![1, 2, 3];

My question is, why would you use or declare an immutable String or Vec like

let myString = String::from("Hello");
let myArray = vec![1, 2, 3];

instead of a true array or str literal like

let myString = "Hello";
let myArray = [1, 2, 3];

What would be the point of that, does it have any benefits? And what may be other use cases for immutable String's and Vec's?

Edit:

Either I am completely missing something obvious or my question isn't fully understood. I get why you want to use a mutable String or Vec over the str literal or an array, since the latter are immutable. But why would one use an immutable String or Vec over the str literal or the array (which are also immutable)?

Upvotes: 2

Views: 1317

Answers (2)

Hellstorm
Hellstorm

Reputation: 650

One use case could be the following:


fn main() {
    let text: [u8; 6] = [0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x00];
    let converted = unsafe { CStr::from_ptr(text.as_ptr() as *const c_char) }.to_string_lossy().to_string();

    println!("{}", converted);
}

This is a bit constructed, but imagine you want to convert a null terminated C string (which might come from the network) from a raw pointer to some Rust string, but you don't know whether it has invalid UTF-8 in it. to_string_lossy() returns a Cow which either points to the original bytes (in case everything is valid UTF-8), but if that's not the case, it will basically copy the string and do a new allocation, replace the invalid characters with the UTF-8 replacement character and then point to that.

This is of course quite nice, because (presumably) most of the time you get away without copying the original C string, but in some cases, it might not be. But if you don't care about that and don't want to work with a Cow, it might make sense to convert it to a String, which you don't need to be mutable afterwards. But it's not possible to have a &str in case the original text contains invalid UTF-8.

Upvotes: 2

lkolbly
lkolbly

Reputation: 1240

You might then do something with that string, for example use it to populate a struct:

struct MyStruct {
    field: String,
}

...

let s = String::from("hello");
let mut mystruct = MyStruct { field: s };

You could also, for example, return it from a function.

Upvotes: 2

Related Questions