[英]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)?如何设置
row
和col
以仅接受(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...您可以通过以下方式表达...
Option<Coord>
Option<Coord>
Row
and Col
, which only accept small values.Row
和Col
,它们只接受小值。 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,因为它只允许从有效的
Row
和Col
值创建 Coord。
In the case of Latitude
Longitude
you would have the same two options.在
Latitude
Longitude
的情况下,您将有相同的两个选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.