Borrow a &Vec<u8> from String

Is there a way to borrow a &Vec> from a String, like if I have my own trait below:

trait BorrowAs {
fn borrow(&self) -> &T;
}

impl BorrowAs<Vec> for String {
fn borrow(&self) -> &Vec {
// implementation code here
}
}

I understand it's ok with [u8] slices.

This is not possible. (There is String::as_mut_vec(), but you can’t call that given only &self.)

In general, it is best to avoid writing Rust code that needs an &Vec<T> (whether that Vec came from a String or not). There is almost nothing that it is good for that an &[T] isn’t better at.

4 Likes

Why do you need a &Vec and not a slice? The only extra thing you can do with it is get the capacity.

2 Likes

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.