用法
pub trait Shl<Rhs = Self> {
type Output;
fn shl(self, rhs:Rhs) -> Self::Output;
}
左移运算符 <<
。请注意,因为这个特征是为所有具有多个 right-hand-side 类型的整数类型实现的,Rust 的类型检查器对 _ << _
有特殊处理,将整数运算的结果类型设置为 left-hand-side 操作数的类型。这意味着尽管a << b
和a.shl(b)
从评估的角度来看是相同的,但在类型推断方面它们是不同的。
例子
Shl
的实现,它将整数上的 <<
操作提升到围绕 usize
的包装器。
use std::ops::Shl;
#[derive(PartialEq, Debug)]
struct Scalar(usize);
impl Shl<Scalar> for Scalar {
type Output = Self;
fn shl(self, Self(rhs):Self) -> Self::Output {
let Self(lhs) = self;
Self(lhs << rhs)
}
}
assert_eq!(Scalar(4) << Scalar(2), Scalar(16));
Shl
的实现,将向量向左旋转给定的量。
use std::ops::Shl;
#[derive(PartialEq, Debug)]
struct SpinVector<T:Clone> {
vec:Vec<T>,
}
impl<T:Clone> Shl<usize> for SpinVector<T> {
type Output = Self;
fn shl(self, rhs:usize) -> Self::Output {
// Rotate the vector by `rhs` places.
let (a, b) = self.vec.split_at(rhs);
let mut spun_vector = vec![];
spun_vector.extend_from_slice(b);
spun_vector.extend_from_slice(a);
Self { vec:spun_vector }
}
}
assert_eq!(SpinVector { vec:vec![0, 1, 2, 3, 4] } << 2,
SpinVector { vec:vec![2, 3, 4, 0, 1] });
相关用法
- Rust std::ops::ShlAssign用法及代码示例
- Rust std::ops::Shr用法及代码示例
- Rust std::ops::ShrAssign用法及代码示例
- Rust std::ops::Sub用法及代码示例
- Rust std::ops::SubAssign用法及代码示例
- Rust std::ops::RangeInclusive.end用法及代码示例
- Rust std::ops::DivAssign用法及代码示例
- Rust std::ops::Try.from_output用法及代码示例
- Rust std::ops::DispatchFromDyn用法及代码示例
- Rust std::ops::Fn用法及代码示例
- Rust std::ops::Not用法及代码示例
- Rust std::ops::RangeBounds.end_bound用法及代码示例
- Rust std::ops::DerefMut用法及代码示例
注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Trait std::ops::Shl。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。