Reputation: 1762
I tried to write a function that takes a generic struct as a parameter:
struct S<T> {
v: T,
}
fn foo(a: &S) {
a.v
}
But an error occurs:
error[E0107]: wrong number of type arguments: expected 1, found 0
--> src/main.rs:5:12
|
5 | fn foo(a: &S) {
| ^ expected 1 type argument
error: aborting due to previous error
After changing to
struct S<T> {
v: T,
}
fn foo<T>(a: &S<T>) -> T {
a.v
}
Another error occurs:
error[E0507]: cannot move out of `a.v` which is behind a shared reference
--> src/main.rs:6:5
|
6 | a.v
| ^^^ move occurs because `a.v` has type `T`, which does not implement the `Copy` trait
error: aborting due to previous error
Finally, I got what I want:
struct S<T> {
v: T,
}
fn foo<T: Copy>(a: &S<T>) -> T {
a.v
}
Upvotes: 1
Views: 84
Reputation: 18401
You missed the generic parameter
struct S<T> {
v: T,
}
fn foo<T>(a: S<T>) -> T {
a.v
}
Or use the Copy bound
fn foo<T: Copy>(a: &S<T>) -> T {
a.v
}
Upvotes: 2