Closed
Description
In the example at the bottom, addition of two arrays yields a new one, but also mutates one of the inputs. This is because the add()
function in the Add
trait is defined in terms of the in-place iadd()
(from the macro impl_binary_op
macro):
impl<'a, A, S, S2, D, E> $trt<&'a ArrayBase<S2, E>> for ArrayBase<S, D>
where A: Clone + $trt<A, Output=A>,
S: DataMut<Elem=A>,
S2: Data<Elem=A>,
D: Dimension,
E: Dimension,
{
type Output = ArrayBase<S, D>;
fn $mth (mut self, rhs: &ArrayBase<S2, E>) -> ArrayBase<S, D>
{
self.$imth(rhs);
self
}
}
This is fine, if self is an OwnedArray
or an Array
because they are consumed anyways, but if instead an ArrayViewMut
is passed in, the underlying data changes. Is this intended? I think one shouldn't expect the array to get changed when addition is performed on a view.
extern crate ndarray;
use ndarray::{Array,OwnedArray};
fn main() {
let r = 0..4;
let v = r.map(|x| x as f64).collect::<Vec<_>>();
let mut a = OwnedArray::from_vec(v.clone()).into_shape((2,2)).unwrap();
let b = OwnedArray::from_vec(v.clone()).into_shape((2,2)).unwrap();
let bv = b.view();
{
let x = a.view_mut() + bv;
println!("{:?}", x);
}
println!("{:?}", a);
}
Metadata
Metadata
Assignees
Labels
No labels