gpt4 book ai didi

generics - 如何为特征的引用指定超特征?

转载 作者:行者123 更新时间:2023-11-29 08:30:39 25 4
gpt4 key购买 nike

我想创建一个特征,强制为类型和对类型的引用实现 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 函数上。

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

关于generics - 如何为特征的引用指定超特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58849618/

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