gpt4 book ai didi

rust - 如何将通用结构作为函数参数

转载 作者:行者123 更新时间:2023-12-03 11:35:12 25 4
gpt4 key购买 nike

我试图编写一个将通用结构作为参数的函数:

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
}

关于rust - 如何将通用结构作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64080840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com