我有一些基本的结构来模拟项目的单位,例如:个,箱,打等。但是我需要让一些字段成为用户必须定义的,而另一些则不需要。这是我使用 Rust 文档中的
default
构造函数实现的。我的问题是 Rust 强制在构造函数中定义所有字段:pub struct Unit {
pub name: String, // this is mandatory. MUST be filled
pub multiplier: f64, // this is mandatory. MUST be filled
pub price_1: Option<f64>, // this is non-mandatory with default value NONE
pub price_2: Option<f64>, // this is non-mandatory with default value NONE
pub price_3: Option<f64>, // this is non-mandatory with default value NONE
}
// here I implement the Default just for the prices.
// If user doesn't fill the name and multiplier field, it will throws an error
// the problem is that Rust forced all of the field to be defined in the constructor
impl Default for Unit {
fn default() -> Unit {
Unit {
price_1: None,
price_2: None,
price_3: None,
}
}
}
let u = Unit {
name: String::from("DOZEN"), // user must fill the name field
multiplier: 20.0, // also the multiplier field
price_1: Some(25600.0), // this is optional, user doesn't have to define this
..Default::default() // call the default function here to populate the rest
}