Rust traits是否可能对其实现的类型的引用施加限制?
我正在尝试编写一个将Rust traits是否可能对其实现的类型的引用施加限制?,rust,Rust,我正在尝试编写一个将整数s减半的通用函数。作为记录,我知道有一个num\u integer::integer特性,我正在我的实际代码中使用它 为了减半,myInteger所需的唯一操作是将引用向右移动一个值。我想在很多地方使用Integers,所以我在Integertrait中捕获了这两个特性,并为其提供了一个通用实现。但是,我仍然需要为我的half函数指定std::ops::Shr 我知道这个问题有两种解决方法。一种是到处指定std::ops::Shr: extern crate num_tr
整数
s减半的通用函数。作为记录,我知道有一个num\u integer::integer
特性,我正在我的实际代码中使用它
为了减半,myInteger
所需的唯一操作是将引用向右移动一个值。我想在很多地方使用Integer
s,所以我在Integer
trait中捕获了这两个特性,并为其提供了一个通用实现。但是,我仍然需要为我的half
函数指定std::ops::Shr
我知道这个问题有两种解决方法。一种是到处指定std::ops::Shr
:
extern crate num_traits;
pub trait Integer
where
Self: num_traits::One,
for<'a> &'a Self: std::ops::Shr<Self, Output = Self>,
{
}
impl<T> Integer for T
where
T: num_traits::One,
for<'a> &'a T: std::ops::Shr<T, Output = T>,
{
}
fn half<N: Integer>(n: &N) -> N
where
for<'a> &'a N: std::ops::Shr<N, Output = N>, // Would like to get rid of this line!
{
n >> num_traits::one()
}
fn main() {
println!("{}", half(&85));
}
是否有其他我没有考虑的替代方案?一个替代方案是将函数移动到trait方法:
pub trait Integer
where
Self: num_traits::One,
for<'a> &'a Self: std::ops::Shr<Self, Output = Self>,
{
fn half(&self) -> Self {
self >> num_traits::one()
}
}
pub-trait-Integer
哪里
Self:num_traits::One,
为了自己{
self>>num_traits::one()
}
}
这并不能真正解决核心问题,但它确实允许您避免再次编写该绑定。我不完全确定,但我认为它应该可以解决这个问题。
pub trait Integer
where
Self: num_traits::One,
for<'a> &'a Self: std::ops::Shr<Self, Output = Self>,
{
fn half(&self) -> Self {
self >> num_traits::one()
}
}