How can I approximate method overloading?

前端 未结 2 1335

I am modeling an API where method overloading would be a good fit. My naïve attempt failed:

// fn attempt_1(_x: i32) {}
// fn attempt_1(_x: f32) {}
// Error:         


        
2条回答
  •  温柔的废话
    2020-12-03 22:15

    Here's another way that drops the enum. It's an iteration on Vladimir's answer.

    trait Tr {
      fn go(&self) -> ();
    }
    
    impl Tr for i32 {
      fn go(&self) {
        println!("i32")
      }
    }
    
    impl Tr for f32 {
      fn go(&self) {
        println!("f32")
      }
    }
    
    fn attempt_1(t: T) {
      t.go()
    }
    
    fn main() {
      attempt_1(1 as i32);
      attempt_1(1 as f32);
    }
    

提交回复
热议问题