我试图编写一个将通用结构作为参数的函数:
struct S<T> {
v: T,
}
fn foo(a: &S) {
a.v
}
但是会发生错误:
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
更改为
struct S<T> {
v: T,
}
fn foo<T>(a: &S<T>) -> T {
a.v
}
发生另一个错误:
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
终于,我得到了我想要的:
struct S<T> {
v: T,
}
fn foo<T: Copy>(a: &S<T>) -> T {
a.v
}
您错过了通用参数
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句