LoginSignup
19
18

More than 5 years have passed since last update.

Rustで関数のオーバーロード

Last updated at Posted at 2018-01-12

Rustには関数のオーバーロード機能はありませんが、それっぽい事をしたい場合、以下のようにすれば出来ます。
※もっと良い方法があったら、教えてください!

trait DoSomething<T> {
    fn do_something(&mut self, c:T);
}

struct DoSomethingImpl {
}

impl DoSomething<i32> for DoSomethingImpl {
    fn do_something(&mut self, c:i32) {
        println!("i32");    
    }
}
impl DoSomething<f32> for DoSomethingImpl {
    fn do_something(&mut self, c:f32) {
        println!("f32");
    }
}

fn main() {
    let mut d = DoSomethingImpl{};

    //引数の型によって自動的に呼ばれる関数が変わる
    DoSomething::do_something(&mut d, 10i32);    //i32
    DoSomething::do_something(&mut d, 1.5f32);    //f32
}

19
18
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
18