realtebo
realtebo

Reputation: 25645

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) ?

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.

Upvotes: 0

Views: 839

Answers (1)

BitTickler
BitTickler

Reputation: 11875

You express this by either...

  1. provide a constructor, which does the checks for valid values and returns an Option<Coord>
  2. create new types Row and Col, which only accept small values. And then use those types in your struct.

ad 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.:

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.

In the case of Latitude Longitude you would have the same two options.

Upvotes: 3

Related Questions