Darshan V
Darshan V

Reputation: 290

How To create fixed size mutable stack allocated string in rust?

Suppose I know the size of a variable which should be stack allocated and be of string type and mutable then how can i create a string type variable that is mutable but of fixed size and hence stack memory is allocated

Using String would give me heap allocated dynamic length variable

Using str would mean i should give the value in compile time itself

Using array of bytes would do it but i will lose functionality associated with string type

Upvotes: 5

Views: 2663

Answers (1)

Cerberus
Cerberus

Reputation: 10217

It's possible to make a &mut str from &mut [u8] with std::str::from_utf8_mut. Example:

fn main() {
    // Just an example of creating byte array with valid UTF-8 contents
    let mut bytes = ['a' as u8; 2];
    // Type annotation is not necessary, added for clarity
    let string: &mut str = std::str::from_utf8_mut(&mut bytes).unwrap();
    // Now we can call methods on `string` which require `&mut str`
    string[0..1].make_ascii_uppercase();
    // ...and the result is observable
    println!("{}", string); // prints "Aa"
}

Playground

Upvotes: 4

Related Questions