I have a vector of objects/instances (not sure what the rust parlance is) which have a field containing a string slice. I need to create an array slice containing the string slice fields. Below is my attempt. I am trying to get foo_bars
to be the same as what_i_want
.
struct Foo<'a> {
bar: &'a str,
}
let foos = vec![Foo { bar: "one" }, Foo { bar: "two" }, Foo { bar: "three" }];
let foo_bars: Vec<str> = foos.into_iter().map(|foo| foo.bar).collect();
let what_i_want = &["one", "two", "three"];
CodePudding user response:
You're missing the &
in Vec<&str>
.
Here's a playground that works.
struct Foo<'a> {
bar: &'a str,
}
fn main() {
let foos = vec![Foo { bar: "one" }, Foo { bar: "two" }, Foo { bar: "three" }];
let foo_bars: Vec<&str> = foos.into_iter().map(|foo| foo.bar).collect();
let what_i_want = &["one", "two", "three"];
println!("{:?}", foo_bars == what_i_want);
}
CodePudding user response:
Everything must have fixed size, str
mean a range of characters in string, And the size of string slice can be very.
You need to use a pointer &
. A pointer is fixed size (usize
). Depend on cpu architecture (32 or 64) bits.
let foo_bars: Vec< str> = foos.into_iter().map(|foo| foo.bar).collect();
^ add a `&` here