A enum type Value has an assertion helper method must_be_int. Following is a tremble implementation for self and &self. How can I define one method instead of repeating myself expect using macro.
pub enum Value {
Int(i32),
String(String),
}
impl Value {
pub fn must_be_int_take_ownership(self) -> i64 {
match self {
Int(i) => i,
_ => panic!("It is not a int"),
}
}
pub fn must_be_int_take_reference(&self) -> &i64 {
match self {
Int(i) => i,
_ => panic!("It is not a int"),
}
}
some function take ownership of Value's associated value. If only defined a take reference method fn must_be_string(&self), then using clone() or to_owned() to transfer a reference type into a ownership one, it will cost a little.
fn consume_value(s: String) {...}
let v = Value::String("hello".to_string());
consume_value(v.must_be_string().clone())