How to create a method taking self or &self instead of creating two methods

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"),
        }
   }

Why would you need to take ownership at all?

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

What's your end goal?

  • Two distinct methods with the same name that return two distinct types
    • Probably you want a trait with method returning an associated type
  • Two distinct methods with the same name that can return one type which is a reference or owned
    • Probably you want a method returning a Cow
  • Two distinct methods with different names but not typing things twice
    • Probably you want the macro
  • Other
2 Likes

Examples of the first two bullets. (It's only on nightly for type_name_of_val to illustrate that it works as intended.)

Thanks for your examples. The trait with method returning an associated type work for me!!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.