简体   繁体   English

在 rust 中,如何限制 struct u8 integer 字段的可能范围?

[英]in rust, how to limit possible range of a struct u8 integer field?

Example例子

pub struct Coord {
    row: u8,
    col: u8,
}

How can I set row and col to be able to accept only values in range (0..3) (so from 0 to 2)?如何设置rowcol以仅接受(0..3)范围内的值(所以从 0 到 2)?

I'd like to force programmer to avoid invalid valued during initializtion.我想强制程序员在初始化期间避免无效值。

Another use case is for Planet Earth coords, where long and latitude have a fixed valid range.另一个用例是地球坐标,其中经度和纬度具有固定的有效范围。

You express this by either...您可以通过以下方式表达...

  1. provide a constructor, which does the checks for valid values and returns an Option<Coord>提供一个构造函数,它检查有效值并返回一个Option<Coord>
  2. create new types Row and Col , which only accept small values.创建新类型RowCol ,它们只接受小值。 And then use those types in your struct.然后在你的结构中使用这些类型。

ad 1.:广告1:

impl Coord {
  pub fn new(row: u8, col: u8) -> Option<Self> {
    if row < 3 && col < 3 {
      Some(Coord { row, col })
    } else {
      None
    }
  }
}

ad 2.:广告 2:

struct Row { 
  value: u8
}
struct Col {
  value: u8
}
impl Row {
  pub fn new(value: u8) -> Option<Row> {
    if value < 3 {
      Some(Row {value})
    } else {
      None
    }
  }
}
impl Col { // ... same as for Row }

// Now the impl for Coord
impl Coord {
  pub fn new(r : Row, c : Col) -> Self {
    Coord { row: r.value, col: c.value }
  }
}

Most would probably opt for solution 1. While some might opt for solution 2, because it only allows creating a Coord from valid Row and Col values.大多数人可能会选择解决方案 1。虽然有些人可能会选择解决方案 2,因为它只允许从有效的RowCol值创建 Coord。

In the case of Latitude Longitude you would have the same two options.Latitude Longitude的情况下,您将有相同的两个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM