Hello, in the following code, it seems y.clone() is unecessary because foo allocate its result completly, why is it disallow ?
mwe :
const N: usize = 10; fn foo(x:&[f64])->Vec<f64> { x.to_vec() } fn main() { let mut y = vec![0.0;N]; let res:[Vec<f64>;N] = from_fn(|n|{ y = foo(&y); y.clone() }); println!("{:?}",res) } One way to avoid this is
let y = vec![0.0;N]; let mut res:[Vec<f64>;N] = from_fn(|_|{ Vec::<f64>::new() }); res[0] = foo(&y); for i in 1..N { res[i] = foo(&res[i - 1]); } println!("{:?}",res) but its not very pretty and it makes unecessary void Vec. Am I missing an helper function to actually makes fixed size array incrementaly ?
claude finds an unsafe way to do this but it uses an non-public contract of from_fn (keeping previous vectors alive)
let y = vec![0.0; N]; let mut prev = y.as_slice() as *const [f64]; let res: [Vec<f64>; N] = from_fn(|_| { let z = foo(unsafe { &*prev }); prev = z.as_slice() as *const [f64]; z }); println!("{:?}", res); 18 posts - 7 participants
