简体   繁体   English

如何为特征的引用指定一个超特征?

[英]How to specify a supertrait for the reference of a trait?

I'd like to create a trait that enforces implementation of the Add trait for both the type and a reference to the type.我想创建一个特征来强制实现类型和类型引用的Add特征。 That is, N + N and &N + &N should both be implemented if using the NumberTrait shown below.也就是说,如果使用如下所示的 NumberTrait,则应该同时实现N + N&N + &N

use std::ops::Add;

// I think a supertrait needs to be added to NumberTrait,
// something like &Add<Output = Self>, but I don't know
// the correct syntax
pub trait NumberTrait: Sized + Add<Output = Self> {}

fn add_number<N: NumberTrait>(a: N, b: N) -> N {
    a + b
}

fn add_number_ref<N: NumberTrait>(a: &N, b: &N) -> N {
    a + b // compiler error occurs in this line: an implementation of `std::ops::Add` might be missing for `&N`
}

You can do something like this:你可以这样做:

use std::ops::Add;

pub trait NumberTrait: Sized + Add<Output = Self>
where
    for<'a> &'a Self: Add<Output = Self>,
{
}

fn add_number<N: NumberTrait>(a: N, b: N) -> N
where
    for<'a> &'a N: Add<Output = N>,
{
    a + b
}

fn add_number_ref<N: NumberTrait>(a: &N, b: &N) -> N
where
    for<'a> &'a N: Add<Output = N>,
{
    a + b
}

But most likely, you don't need that constraint everywhere, and you could just put where clause on the add_number_ref function.但最有可能的是,您不需要到处都使用该约束,您可以将 where 子句放在add_number_ref function 上。

See: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b5bdd3633d22ea1e0873d431a6665f9d参见: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b5bdd3633d22ea1e0873d431a6665f9d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在特征本身上写一个特征绑定来引用关联类型? - How to write a trait bound for a reference to an associated type on the trait itself? 如何为类型引用的操作指定通用特征? - How do I specify a generic trait for operations on references to types? 如何从盒装特征 object 中获取对结构的引用? - How to get reference to struct from boxed trait object? 如何在特征绑定中指定`std :: ops :: Mul`的预期结果? - How do I specify the expected result of a `std::ops::Mul` in a trait bound? 当 args 不受约束时,如何为实现 trait Fn 的类型指定泛型参数? - How to specify a generic argument for a type that implements trait Fn when the args are not constrained? 如果在函数内创建引用,如何将泛型类型与需要使用生命周期参数的特征绑定在一起? - How do I bound a generic type with a trait that requires a lifetime parameter if I create the reference inside the function? 需要从案例类的特征中引用同伴对象的特征 - Need to Reference Trait on Companion Object From Trait on Case Class 通用超特征/需要一揽子实现 - Generic supertrait / requiring blanket impl 如何在特征中定义隐式写入 - How to define implicit Writes in trait 如何实现泛型类型的特征? - How to implement a trait for generic type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM