简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM