-
Notifications
You must be signed in to change notification settings - Fork 307
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Best Practice: ArrayView vs Pointer #1059
Comments
I'm just a user, not a dev, but here's my take. Firstly you should understand that an My second general point is that, since all array subtypes are just Now to your questions:
Neither. As mentioned above, if your function doesn't care what type of array it takes, it should be made generic over
Follow Rust best practices here, and use the lowest level of ownership you can. If your function doesn't mutate the array, just accept a borrowed fn sum<A, S, D>(a: &ArrayBase<S, D>) -> A
where
S: Data<Elem = A>,
D: Dimension; And indeed this is basically how it's implemented in ndarray/src/numeric/impl_numeric.rs Lines 19 to 49 in 87506b8
Remember, if your function takes an
As explained, no, making it generic over
No. See my first paragraph. |
Thanks for your detailed answer 😄 I will refactor some of my code to be a bit more general and use Perhaps there should be some part of the documentation that addresses this to make it clearer? Or if that exists somewhere, I didn't see it. Note that whether I pass in |
This is true, it's not the safety that makes this unadvisable, it's the fact that you're requesting more ownership in your function than you need, and users will be annoyed that they have to re-create the view in their code since your function consumes it. |
#879 has some discussion about this question and a proposal to improve |
@jturner314 Thanks for the link to the RFC! This looks like a very promising change for the next major release of ndarray. |
I was wondering whether there was a best practive when writing functions that expect arrays, specifically when they are not taking ownership of the array. I couldn't see this being addressed in the documentation or in an existing issue so here's a few things I think could be worth thinking about:
Should functions prefer to take
ArrayView
over the equivalentArray
, and what about using a pointer vs by value? For example, which of the following would be 'best'?When muteable data is expected, is there a preference to using
ArrayViewMut
vs&mut Array
?I would expect that for most applications, the
ArrayView
andArrayViewMut
are preferred as they are more general.Is the fact that they are views into an array mean that they behave more like pointers and thus
&ArrayView
is redundant?The text was updated successfully, but these errors were encountered: