我有一个结构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如何提供泛型结构的实现?我应该把泛型参数及其约束放在哪里?
发布于 2019-02-03 20:22:35
类型参数<T: SomeTrait>应该紧跟在impl关键字之后:
impl<T: SomeTrait> MyStruct<T> {
fn new(t: T) -> Self {
MyStruct { value: t }
}
}如果impl<...>中的类型和约束列表过长,则可以使用where-syntax并分别列出约束:
impl<T> MyStruct<T>
where
T: SomeTrait,
{
fn new(t: T) -> Self {
MyStruct { value: t }
}
}注意Self的用法,它是MyStruct<T>在impl块中可用的快捷方式。
备注
impl<T>的原因在this answer中解释了。本质上,它归结为这样一个事实,即impl<T> MyStruct<T>和impl MyStruct<T>都是有效的,但含义不同。new移动到impl块中时,您应该删除多余的类型参数,否则您的结构的接口将变得不可用,如下例所示:
//特质SomeTrait和结构MyStruct如上// .impl,其中T: SomeTrait,{ fn new(t: S) -> MyStruct { MyStruct { value: t}}-> SomeTrait for u64 {} impl SomeTrait for u128 {} fn main() { //只是问题代码的演示,不要这样做!设a: MyStruct =MyStruct:new:(1234);// ^ // AC.26 //这是一个不能推断的无关类型//。编译器//不仅会强迫您提供一个不相关的类型,还会//不会阻止您将不连贯的垃圾作为类型//参数传递,如本例所示。这种情况发生//是因为S和T完全无关。}https://stackoverflow.com/questions/54504026
复制相似问题