![](/img/trans.png)
[英]How to write a trait bound for a reference to an associated type on the trait itself?
[英]How to specify a supertrait for the reference of a trait?
我想創建一個特征來強制實現類型和類型引用的Add
特征。 也就是說,如果使用如下所示的 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`
}
你可以這樣做:
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
}
但最有可能的是,您不需要到處都使用該約束,您可以將 where 子句放在add_number_ref
function 上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.