当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust Shl用法及代码示例


本文简要介绍rust语言中 Trait std::ops::Shl 的用法。

用法

pub trait Shl<Rhs = Self> {
    type Output;
    fn shl(self, rhs: Rhs) -> Self::Output;
}

左移运算符 << 。请注意,由于此特征是针对具有多个右侧类型的所有整数类型实现的,因此 Rust 的类型检查器对 _ << _ 有特殊处理,将整数运算的结果类型设置为左侧操作数的类型。这意味着虽然 a << ba.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-lang.org大神的英文原创作品 Trait std::ops::Shl。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。