在 Rust 中实现命名颜色的最佳方法是什么?

问题描述 投票:0回答:1

(我是一个 Rust 新手,有很强的 C/C++/Java 背景。)

我希望能够做这样的事情:

struct MyColor {
  Red : u8,
  Green : u8,
  Blue : u9,
}

#[repr(MyColor)]
enum PrimaryColors {
  Red (255,0,0)
  Green (0,255,0)
  Blue (0, 0, 255)
}

然后在我的程序中我可以访问

PrimaryColors::Red::Green
并得到 0,或者可能做类似的事情
(r,g,b) = PrimaryColors::Red

我可以想象这种东西的许多用途(例如拥有资本、人口等的国家列表)。

我已经编写了许多小程序,试图理解错误和建议,但我开始重复自己。

是否有专家愿意说:“哦,你只需要做......”? 我知道枚举可能不是 Rust 中的正确机制。

谢谢!

rust enums structure
1个回答
0
投票

您可以使用关联的

const
来执行此操作:

struct MyColor {
    red: u8,
    green: u8,
    blue: u8,
}

impl MyColor {
    pub const fn new(red: u8, green: u8, blue: u8) -> Self {
        Self { red, green, blue }
    }

    pub const RED: Self = Self::new(255, 0, 0);
    pub const GREEN: Self = Self::new(0, 255, 0);
    pub const BLUE: Self = Self::new(0, 0, 255);
}
例如,现在您可以使用

MyColor::RED

。  如果您希望它们以其他名称可用,例如示例中的 
PrimaryColors
,则只需使用模块:

mod PrimaryColors { use super::MyColor; pub const RED: MyColor = MyColor::new(255, 0, 0); pub const GREEN: MyColor = MyColor::new(0, 255, 0); pub const BLUE: MyColor = MyColor::new(0, 0, 255); }
    
© www.soinside.com 2019 - 2024. All rights reserved.