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


Rust Neg用法及代码示例

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

用法

pub trait Neg {
    type Output;
    fn neg(self) -> Self::Output;
}

一元否定运算符 -

例子

SignNeg 的实现,它允许使用 - 来否定其值。

use std::ops::Neg;

#[derive(Debug, PartialEq)]
enum Sign {
    Negative,
    Zero,
    Positive,
}

impl Neg for Sign {
    type Output = Self;

    fn neg(self) -> Self::Output {
        match self {
            Sign::Negative => Sign::Positive,
            Sign::Zero => Sign::Zero,
            Sign::Positive => Sign::Negative,
        }
    }
}

// A negative positive is a negative.
assert_eq!(-Sign::Positive, Sign::Negative);
// A double negative is a positive.
assert_eq!(-Sign::Negative, Sign::Positive);
// Zero is its own negation.
assert_eq!(-Sign::Zero, Sign::Zero);

相关用法


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