I have a String and I want to update the value of a character in a specific index of the string. I know the index I'm going to update exists in the string because of my input type. My first idea was to get a mutable reference to the slice in the index I want, like this:
let mut s = "foo".to_owned();
let index = s.get_mut(1..1).unwrap();
*index = "b";
println!("{}", s);
but the compiler won't let me:
he size for values of type `str` cannot be known at compilation time
doesn't have a size known at compile-time
help: the trait `std::marker::Sized` is not implemented for `str`
What I could manage to do was change the exact byte using the unsafe as_bytes_mut
:
let mut s = "foo".to_owned();
unsafe {
let bytes = s.as_bytes_mut();
let index = &mut bytes[2..3];
'b'.encode_utf8(index);
}
println!("{}", s); // fob
Can I do it without using unsafe code though?