On Sun, Oct 6, 2013 at 5:09 AM, Rémi Fontan <remifon...@yahoo.fr> wrote:

> Hi,
>
> I have just moved some of my code from 0.6 to rust 0.8 and was
> surprisingly not too difficult, great!
>
> however I noticed while converting copy to clone that I have to use a lot
> of explicit calls to ".clone()" in my templated code. In non templated
> code, the compiler is apparently more forgiving.
>
> Here' s a simple example to illustrate my point. Do you understand why I
> must write the initialisation of the list as "data:[a.clone(), a.clone(),
> a.clone()] " in the templated code and not simply "data:[a, a, a]". As T
> implements the clone trait, I was hoping the compiler would automatically
> clone when required.
>
> struct mystruct {
>     data : [float, ..3]
> }
>
> impl mystruct {
>     pub fn new(a:float) -> mystruct {
>         mystruct{ data:[a, a, a] }
>     }
> }
>
> struct mytmplstruct<T> {
>     data : [T, ..3]
> }
>
> impl<T:Real+Clone> mytmplstruct<T> {
>
>     pub fn new(a:T) -> mytmplstruct<T> {
>         mytmplstruct{ data:[a.clone(), a.clone(), a.clone()] }
>     }
> }
>
> #[test]
> fn test_structs() {
>     let m1 = mystruct::new(1.234f);
>     let m2 = mytmplstruct::new(1.234f);
> }
>
>
> cheers,
>
> Rémi
>

The `Clone` trait is entirely a library feature, so the compiler will never
automatically generate calls to it. Rust has by-value assignment, passing
and returning built into the language, but for some types (anything with a
destructor, &fn or &mut) it moves ownership.

In a generic function, it is always assumed to move ownership, as there is
no trait associated with whether types move or not. I don't think it would
be useful to have one, because `Clone` is much more generic.

One minor nitpick is that with `[a.clone(), a.clone(), a.clone()]` you're
not taking advantage of the existing value you have. You can move the value
you do own into the array after the 2 clones. Otherwise, there's not much
point in taking it by-value (although you do want that, if you would
otherwise need to make at least one more copy).
_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to