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


Rust BitOr用法及代码示例


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

用法

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

按位或运算符 |

请注意,Rhs 默认为 Self,但这不是强制性的。

例子

BitOr 的实现,用于围绕 bool 的包装。

use std::ops::BitOr;

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

impl BitOr for Scalar {
    type Output = Self;

    // rhs is the "right-hand side" of the expression `a | b`
    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

assert_eq!(Scalar(true) | Scalar(true), Scalar(true));
assert_eq!(Scalar(true) | Scalar(false), Scalar(true));
assert_eq!(Scalar(false) | Scalar(true), Scalar(true));
assert_eq!(Scalar(false) | Scalar(false), Scalar(false));

BitOr 的实现,用于围绕 Vec<bool> 的包装。

use std::ops::BitOr;

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

impl BitOr for BooleanVector {
    type Output = Self;

    fn bitor(self, Self(rhs): Self) -> Self::Output {
        let Self(lhs) = self;
        assert_eq!(lhs.len(), rhs.len());
        Self(
            lhs.iter()
                .zip(rhs.iter())
                .map(|(x, y)| *x | *y)
                .collect()
        )
    }
}

let bv1 = BooleanVector(vec![true, true, false, false]);
let bv2 = BooleanVector(vec![true, false, true, false]);
let expected = BooleanVector(vec![true, true, true, false]);
assert_eq!(bv1 | bv2, expected);

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Trait std::ops::BitOr。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。