This code works:
let mut b: Vec<*const SimpleStruct> = Vec::with_capacity(a.len());
for val in a.iter() {
b.push(val);
}
This code does not work:
let b: Vec<*const SimpleStruct> = a.iter().map(|val| val).collect();
Why is this?
This code works:
let mut b: Vec<*const SimpleStruct> = Vec::with_capacity(a.len());
for val in a.iter() {
b.push(val);
}
This code does not work:
let b: Vec<*const SimpleStruct> = a.iter().map(|val| val).collect();
Why is this?
When you push &SimpleStruct
to a Vec<*const SimpleStruct>
, Rust knows that it can coerce the reference into a pointer. However, when you collect
it, Rust is trying to coerce a Vec<&SimpleStruct>
to a Vec<*const SimpleStruct>
, which it can't do, so you should be more explicit:
let b: Vec<*const SimpleStruct> = a.iter().map(|val| val as *const SimpleStruct).collect();
or
let b: Vec<*const SimpleStruct> = a.iter().map(|val| -> *const SimpleStruct { val }).collect();