What is the best way to convert a Vec to an array in the latest versions of rust? (Assuming that the type inside the Vec is the same type you need in the array.)
i.e. to resolve errors such as:
error[E0308]: mismatched types
--> src/form.rs:96:20
|
96 | gloss: &gloss,
| ^^^^^^ expected `&[&Gloss<'_>]`, found `&Vec<Gloss<'_>>`
|
= note: expected reference `&[&gloss::Gloss<'_>]`
found reference `&Vec<gloss::Gloss<'_>>`
Or:
error[E0308]: mismatched types
--> src/lexeme.rs:58:24
|
58 | gloss: &entry,
| ^^^^^^ expected `&[&str]`, found `&Vec<&&str>`
|
= note: expected reference `&[&str]`
found reference `&Vec<&&str>`
(I have a build.rs file that is parsing text input and creating static/const arrays that will never change, so I can't use Vec
in the struct's)
This is not turning a Vec
into an array. You are attempting to turn a Vec
of owned values into a slice of references. They contain different types so the conversion can not be made without allocating additional space. You likely need to update your function signature to accept &[Gloss<'_>]
instead of &[&Gloss<'_>]
.
Using &[&str]
is fine, but Vec<&&str>
seems like it may be a mistake due to the double reference. Perhaps you are collecting from an iterator of &&str
?
No conversion is needed if you get the types correct. i.e.
pub struct MyStruct<'a> {
items: &'a [&'a str],
gloss: &'a [Gloss<'a>], // not &Gloss
}
...
let mut items: Vec<&str> = Vec::new();
let mut glosses: Vec<Gloss> = Vec::new();
...
let i = MyStruct{
items: &items,
gloss: &glosses,
}