Trait core::ops::BitAndAssign1.8.0[][src]

pub trait BitAndAssign<Rhs = Self> {
    fn bitand_assign(&mut self, rhs: Rhs);
}
Expand description

按位与分配运算符 &=

Examples

BitAndAssign 的实现,将 &= 运算符提升为 bool 的包装器。

use std::ops::BitAndAssign;

#[derive(Debug, PartialEq)]
struct Scalar(bool);

impl BitAndAssign for Scalar {
    // rhs 是表达式 `a &= b` 的 "right-hand side"
    fn bitand_assign(&mut self, rhs: Self) {
        *self = Self(self.0 & rhs.0)
    }
}

let mut scalar = Scalar(true);
scalar &= Scalar(true);
assert_eq!(scalar, Scalar(true));

let mut scalar = Scalar(true);
scalar &= Scalar(false);
assert_eq!(scalar, Scalar(false));

let mut scalar = Scalar(false);
scalar &= Scalar(true);
assert_eq!(scalar, Scalar(false));

let mut scalar = Scalar(false);
scalar &= Scalar(false);
assert_eq!(scalar, Scalar(false));
Run

这里,BitAndAssign trait 是为 Vec<bool> 周围的包装器实现的。

use std::ops::BitAndAssign;

#[derive(Debug, PartialEq)]
struct BooleanVector(Vec<bool>);

impl BitAndAssign for BooleanVector {
    // `rhs` 是表达式 `a &= b` 的 "right-hand side"。
    fn bitand_assign(&mut self, rhs: Self) {
        assert_eq!(self.0.len(), rhs.0.len());
        *self = Self(
            self.0
                .iter()
                .zip(rhs.0.iter())
                .map(|(x, y)| *x & *y)
                .collect()
        );
    }
}

let mut bv = BooleanVector(vec![true, true, false, false]);
bv &= BooleanVector(vec![true, false, true, false]);
let expected = BooleanVector(vec![true, false, false, false]);
assert_eq!(bv, expected);
Run

Required methods

执行 &= 操作。

Examples

let mut x = true;
x &= false;
assert_eq!(x, false);

let mut x = true;
x &= true;
assert_eq!(x, true);

let mut x: u8 = 5;
x &= 1;
assert_eq!(x, 1);

let mut x: u8 = 5;
x &= 2;
assert_eq!(x, 0);
Run

Implementors