0

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?

danitrod
  • 401
  • 5
  • 10
  • 3
    See [Modifying chars in a String by index](https://stackoverflow.com/questions/26544542/modifying-chars-in-a-string-by-index) – Rabbid76 Feb 18 '21 at 21:58
  • Awesome, don't know why I couldn't find it searching - solves my question. Thanks! – danitrod Feb 18 '21 at 22:33
  • 1
    Unless I'm missing something, this can be done with [`replace_range`](https://doc.rust-lang.org/std/string/struct.String.html#method.replace_range). See it working on the [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bc82eefb2b782f5a56a6d27303c43c25) – kmdreko Feb 19 '21 at 07:13

0 Answers0