S
S
Somewhere Intech2019-03-05 09:34:00
Rust
Somewhere Intech, 2019-03-05 09:34:00

How to make rustc clone dynamic type variables?

I started to get acquainted with rust and I can't understand "the vaunted magic of traits" in any way.
The task is simple, I want a structure with a dynamic type, for example i32 or f64. Rust doesn't know the size of T and can't copy it.. that's OK!
The book describes an example of using trait with an explicit data type.

he works
5c7e180d72814659884879.png

Tried to repeat -
FAIL
5c7e18465db43117501029.png

What did I do wrong - I can not understand

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Lesnikov, 2019-03-05
@john36allTa

(No need to throw the code with a picture)
MCVE for your error looks like this:

fn foo<T>(a: T) -> (T, T) {
    (a, a)
}

fn main() {
    foo(1);
}

playground
As it is written in the error, the fact is that the `T` type you use does not require the marker type Copy , which means that variables with its type are moved to the structure field for the first time, i.e. there is nothing to put in the second field.
The easiest way to correct errors in this case is to add a Copy requirement:
fn foo<T: Copy>(a: T) -> (T, T) {
    (a, a)
}

Playground
But the Copy trait only works for POD types , for more complex types in this situation you need the Clone trait .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question