Rfcs: &Vec<String> -> &[&str]

Created on 21 Jun 2018  路  3Comments  路  Source: rust-lang/rfcs

&String automagically casts itself to &str when passed into a function that expects &str.

Vec<T> is automagically casted to &[T] when passed into a function that expects &[T].

Is there a way to add to the compiler a way to automagically cast Vec<String> into &[&str]? I assume that lifetime of the &str should be equal to the lifetime of the slice.

Most helpful comment

This is not possible because &str is not layout-compatible with String. You would have to allocate a new array on the heap and fill it with str references created from the Strings in the Vec.

All 3 comments

This form of automagic is called "deref coercions": https://doc.rust-lang.org/book/second-edition/ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods The key detail is that it's only references like &Vec<T> and &String that automagically become &[T] and &str, never just Vec<T> or just String.

~For the actual suggestion here, if the intuition is that "deref coercions should nest", I think that would only really apply to &Vec<&String>, not to Vec<String> or &Vec<String>. Plus, converting any of those three into a &[&str] requires touching every element of the Vec, which seems like a bit more work than deref coercions are really supposed to do. So I'm not sure if this is actually feasible.~ Actually, what @Diggsey said is the real problem.

This is not possible because &str is not layout-compatible with String. You would have to allocate a new array on the heap and fill it with str references created from the Strings in the Vec.

Closing since the question is already answered as not possible.

Taking a step back however, if you鈥檙e writing the function or method that receives this value you can make it generic like this:

```rust
fn foo>(v: &[S]) {
for s in v {
let s = s.as_ref();
// s has type &str
}
}

foo(&["this is &str"])
foo(&vec!["this is &str"])
foo(&["this is String".to_string()])
foo(&vec!["this is String".to_string()])

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ekleog picture Ekleog  路  204Comments

Ericson2314 picture Ericson2314  路  69Comments

sfackler picture sfackler  路  167Comments

steveklabnik picture steveklabnik  路  69Comments

pnkfelix picture pnkfelix  路  160Comments