如何在 Rust 中创建固定大小的可变堆栈分配字符串?

Dar*_*n V 5 string memory-management utf-8 char rust

假设我知道应该分配堆栈且为字符串类型可变的变量的大小,那么我如何创建一个可变但大小固定的字符串类型变量,从而分配堆栈内存

使用String会给我堆分配的动态长度变量

使用str 意味着我应该在编译时本身给出值

使用字节数组可以做到这一点,但我将失去与字符串类型相关的功能

Cer*_*rus 4

可以使用来制作&mut strfrom 。例子:&mut [u8]std::str::from_utf8_mut

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"
}
Run Code Online (Sandbox Code Playgroud)

操场