我有一个 struct MyStruct
,它接受一个通用参数T: SomeTrait
,我想为MyStruct
实现一个new
方法.这是有效的:
/// Constraint for the type parameter `T` in MyStruct
pub trait SomeTrait: Clone {}
/// The struct that I want to construct with `new`
pub struct MyStruct<T: SomeTrait> {
value: T,
}
fn new<T: SomeTrait>(t: T) -> MyStruct<T> {
MyStruct { value: t }
}
fn main() {}
我想把new
函数放在impl
块中,如下所示:
impl MyStruct {
fn new<T: SomeTrait>(t: T) -> MyStruct<T> {
MyStruct { value: t }
}
}
但这并不能用:
error[E0107]: wrong number of type arguments: expected 1, found 0
--> src/main.rs:9:6
|
9 | impl MyStruct {
| ^^^^^^^^ expected 1 type argument
如果我试着这样说:
impl MyStruct<T> {
fn new(t: T) -> MyStruct<T> {
MyStruct { value: t }
}
}
错误更改为:
error[E0412]: cannot find type `T` in this scope
--> src/main.rs:9:15
|
9 | impl MyStruct<T> {
| ^ not found in this scope
如何提供通用 struct 的实现?我应该把通用参数及其约束放在哪里?