私はInteger
の半分の汎用関数を書こうとしています。記録のために、私はnum_integer::Integer
特性があり、私はそれを私の実際のコードで使用していることを知っています。形質が実装されている型への参照に制限を課す可能性はありますか?
半分にするために、私のInteger
が必要とする操作は、右と1つの値への参照をシフトする機能です。私は多くの場所でInteger
を使用したいので、私はInteger
形質でこれらの2つの特性を捕捉し、それに対する一般的な実装を提供します。しかし、私のhalf
機能にはまだstd::ops::Shr
を指定する必要があります。
この問題の2つの回避策を知っています。一つは、どこにでも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));
}
別のオプションは、half
がそれを借りるのではなく、その引数を消費することです、その場合には、私が代わりに参照の値をシフトすることだし、問題はラインがもはや必要ではありませんコメント:
extern crate num_traits;
pub trait Integer
where
Self: num_traits::One,
Self: std::ops::Shr<Self, Output = Self>,
{
}
impl<T> Integer for T
where
T: num_traits::One,
T: std::ops::Shr<T, Output = T>,
{
}
fn half<N: Integer>(n: N) -> N {
n >> num_traits::one()
}
fn main() {
println!("{}", half(85));
}
私が考慮していない他の選択肢はありますか?
私は完全にはわかりませんが、[Implied bounds(RFC 2089)](https://github.com/rust-lang/rust/issues/44491)はこれを修正することになっています。 – Stefan