Trying to modify Strings

Hello,

I'm trying to write code that does the following:

//someString = "ABC"
let mut newString = someString.insert(1,c);
// c = 'A'

So the end result would be: newString = AABC

However, for some reason, using insert changes newString from being a String and turns it into ().

Hopefully someone can help me understand what I'm missing? I've been using Rust for just a couple of weeks.

Many thanks

Hi, insert modifies the string in place that's why you have (), the documentation of the unit type explains it.
If your string is mutable you can simply do:

someString.insert(1, c);

and the string will be modified. If you don't want to modify someString and/or it's immutable you can do:

let mut newString = someString.clone();
newString.insert(1, c);

or more complicated but probably with better performance:

let mut newString = String::with_capacity(someString.capacity() + c.len_utf8());
newString.push_str(&someString[0..1]);
newString.push(c);
newString.push_str(&someString[1..]);

I can't think of a way to have a pretty and efficient version but I'm curious to see what other people will propose.

2 Likes

insert modifies the String in-place, it doesn't return any useful value. If you print someString after calling insert you'll see that it was mutated.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.