[rust-dev] Passing arguments bu reference

Daniel Micay danielmicay at gmail.com
Sun Jun 1 01:41:21 PDT 2014

On 01/06/14 04:34 AM, Christophe Pedretti wrote:
> Hello all,
> I've read this :
> http://words.steveklabnik.com/pointers-in-rust-a-guide
> I am coming from Java where everything is passed and returned by
> reference (except for primitive data types), no choice.
> I know that with C, you have to use pointers to avoid passing and
> returning by value.
> When i read the mentionned guide, things are not so evident with Rust.
> So, to be precise, imagine i need to write à fonction which takes à
> big Vec<u8> (In my case it´s an SQL BLOB) as argument and returns a
> big Vec<u8>
> Should i use
> Fn my_func(src : &Vec<u8>) -> &Vec<u8>
> Fn my_func(src : &Vec<u8>) -> ~Vec<u8>
> Fn my_func(src : &Vec<u8>) ->Vec<u8>
> Fn my_func(src : Vec<u8>) -> Vec<u8>
> Fn my_func(src : ~Vec<u8>) -> ~Vec<u8>
> Any other combination ?
> Thanks
> PS : i know that i have to use lifetimes and that ~ are now Box, i've
> omitted them to simplify my demand
> PS2 : genrally with a language you can accomplish the same thing with
> different methods, but there are also common "usages", even if Rust is
> young, what is the usage for passing and returning large data values

Vec<T> is always { ptr, len, cap }, it's never larger than 3 words.

Rust *always* passes, assigns and returns exactly as C would. It's a
shallow copy and never runs any magical operations as it can in C++.

You should pass it by-value if the function needs to own a copy of the
vector, and otherwise pass `&[T]` or `&mut [T]`. Using `&Vec<T>` is an
anti-pattern because it offers nothing over `&[T]` and is just less
general. It does make sense to use `&mut Vec<T>` if you want to alter
the length in the function without taking ownership.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140601/fa212382/attachment.sig>

More information about the Rust-dev mailing list