R) --6ren">
gpt4 book ai didi

generics - "generic parameters of trait function"和 "generic parameters of trait"有什么区别?

转载 作者:行者123 更新时间:2023-12-03 16:57:34 27 4
gpt4 key购买 nike

generic parameters of trait function 的简单示例:

trait Ext: Sized {
fn then<R>(self, f: fn(Self) -> R) -> R {
f(self)
}
}

impl<T> Ext for T {}
generic parameters of trait 的简单示例:
trait Ext<R>: Sized {
fn then(self, f: fn(Self) -> R) -> R {
f(self)
}
}

impl<T, R> Ext<R> for T {}
两者有什么区别?
什么时候应该使用“特征函数的通用参数”,什么时候应该使用“特征的通用参数”?

最佳答案

如果您在特征上使用泛型参数,那么相同的值将必须应用于特征实现中的所有函数,而不是仅应用于每个函数,但您还必须在引用特征时指定参数。
这样做的一个优点是您可以为该 trait 参数的特定值实现一个 trait,其中每个实现都是独立的:

impl Ext<String> for Something { }
impl Ext<u32> for Something { }
也可以根据特征参数限制类型。例如,对于 Mul 特征:
pub trait Mul<Rhs = Self> {
type Output;
pub fn mul(self, rhs: Rhs) -> Self::Output;
}
特定类型的实现将确定 Self 的类型,并且它必须指定 Self::Output(不必与 type 相同)。这里的 trait 参数是确保 rhs 的类型与 Self 相同

关于generics - "generic parameters of trait function"和 "generic parameters of trait"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66769488/

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