2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rustで関数オーバーロードをする

Posted at

やりたいこと

Rustで関数の引数によって処理を分ける

トレイトを使い、引数にトレイト境界を持たせる実装は色々なところで議論されている。

今回実装したのは、引数の型だけでなく、引数の個数でも実装を変える方法だ。

trait Print {
    fn print(&self);
}

impl Print for &str {
    fn print(&self) {
        println!("&str: {}", self);
    }
}

impl Print for i32 {
    fn print(&self) {
        println!("i32: {}", self);
    }
}

impl Print for (&str, i32) {
    fn print(&self) {
        let (s, i) = self;

        println!("&str: {}, i32: {}", s, i);
    }
}

macro_rules! print {
    ($($value: expr),+) => {
        {
            ($($value),+).print()
        }
    };
}

fn main() {
    print!("str");
    print!(10);
    print!("str", 10);
}

タプルにトレイトを実装し、マクロを使って引数をタプルにしてメソッドを実行することで、引数の個数による実装を分けている。

2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?