Why does `String` not have a `set_len` method like `Vec`?

I'm trying to assemble a String from a raw pointer and a size. I'm currently using an intermediate Vec just because of its set_len function which String doesn't seem to have (ptr is a *const c_char):

let mut buf = Vec::<u8>::with_capacity(size);
ptr::copy(ptr as *const u8, buf.as_mut_ptr(), size);
buf.set_len(size);
let str = StdString::from_utf8_unchecked(buf);

but I'd like to do:

let mut str = StdString::with_capacity(size);
ptr::copy(ptr as *const u8, str.as_mut_ptr(), size);
str.set_len(size);

I think the reason is that it's considered fine to use the intermediate vec, because it's just not that common of a need.

There are other ways you could do this as well, like getting a &str to your buffer, and calling .to_owned() on that.

I suppose you could also do str.as_mut_vec().set_len(size);, right?

5 Likes

Wow, that's been there since Rust 1.0 and I've never noticed it!

1 Like

Yep, missed that function :sweat_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.