&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.
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 String
s 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
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()])
Most helpful comment
This is not possible because
&str
is not layout-compatible withString
. You would have to allocate a new array on the heap and fill it withstr
references created from theString
s in theVec
.