Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust traits是否可能对其实现的类型的引用施加限制?_Rust - Fatal编程技术网

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
特性,我正在我的实际代码中使用它

为了减半,my
Integer
所需的唯一操作是将引用向右移动一个值。我想在很多地方使用
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()
    }
}