我正在尝试更新 achar中的 a String,但似乎无法做到这一点。
fn main() {
let mut s = "poyo".to_string();
// s[1] = 'i'; or s.get_mut(1) = 'i'; can't do either
println!("{}", s); // expecting "piyo"
}
Run Code Online (Sandbox Code Playgroud)
我知道为什么会发生这种情况(String没有实现IndexMut<usize>),但我不知道如何解决这个问题...
答案取决于String您要处理的类型;如果您正在使用ASCII工作只(这意味着每个字符的大小是一个字节,你可以直接操纵底层Vec<u8>),你可以做到以下几点:
fn main() {
let mut s = "poyo".to_string();
let mut bytes = s.into_bytes();
bytes[1] = 'i' as u8;
unsafe { s = String::from_utf8_unchecked(bytes) }
println!("{}", s);
}
Run Code Online (Sandbox Code Playgroud)
或者:
fn main() {
let mut s = "poyo".to_string();
unsafe {
let bytes = s.as_bytes_mut();
bytes[1] = 'i' as u8;
}
println!("{}", s);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您(可能)使用多字节字符(这就是为什么String不实现IndexMut甚至不实现的全部原因Index),那么安全的方法是使用Chars迭代器,遍历它并创建一个新的String基于其元素:
fn main() {
let s = "poyo".to_string();
let iter = s.chars();
let mut new = String::new();
for (i, mut c) in iter.enumerate() {
if i == 1 { c = 'i'; }
new.push(c);
}
println!("{}", new);
}
Run Code Online (Sandbox Code Playgroud)