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

【Effective-Rustlings-jp】Day 16:ワイルドカードインポートを避けよう

Last updated at Posted at 2025-01-22

はじめに

こんにちは。細々とプログラミングをしているsotanengelです。
この記事は以下の記事の連載です。

他の連載記事 (詳細)

また本記事はEffective Rust(David Drysdale (著), 中田 秀基 (翻訳))を参考に作成されております。とてもいい書籍ですので興味を持った方は、ぜひ読んでみてください!

今日の内容

概要

Rustではワイルドカード(*)を使って一連のアイテムを取り込むことができます。
ただしワイルドカードを使ったインポートには問題点もあります。

ワイルドカードインポートを避けて実装しよう

問(リンク)

同じトレイト名が実装されているため、名前が衝突してしまっています。
明示的にインポートすることで問題を解消しましょう。

コード (詳細)
mod module_a {
    pub trait MyTrait {
        fn foo(&self);
    }
}

mod module_b {
    #[allow(dead_code)]
    pub trait MyTrait {
        fn bar(&self);
    }

    pub trait AnotherTrait {
        fn baz(&self);
    }
}

// TODO: ワイルドカードを使ってしまったため、トレイト名が衝突してしまっています。
//       明示的にインポートをすることで問題を解消してください。
use module_a::*;
use module_b::*;

struct MyStruct;

impl MyTrait for MyStruct {
    fn foo(&self) {
        println!("Foo from module_a");
    }
}

// module_b の AnotherTrait を MyStruct に対して実装
impl AnotherTrait for MyStruct {
    fn baz(&self) {
        println!("Baz from module_b");
    }
}

fn main() {
    let s = MyStruct;
    s.foo();
    s.baz();
}

解答(リンク)

コード参照。
書籍上では以下のような場合に問題が起きるとされているため、ワイルドカードは避けた方がいいと思われる。

  • インポートしているクレートやモジュールが更新され、ローカルで使用している名前と合致してしまう
コード (詳細)
mod module_a {
    pub trait MyTrait {
        fn foo(&self);
    }
}

mod module_b {
    #[allow(dead_code)]
    pub trait MyTrait {
        fn bar(&self);
    }

    pub trait AnotherTrait {
        fn baz(&self);
    }
}

// ワイルドカードを使わずに指定する
use module_a::MyTrait;
use module_b::AnotherTrait;

struct MyStruct;

impl MyTrait for MyStruct {
    fn foo(&self) {
        println!("Foo from module_a");
    }
}

// module_b の AnotherTrait を MyStruct に対して実装
impl AnotherTrait for MyStruct {
    fn baz(&self) {
        println!("Baz from module_b");
    }
}

fn main() {
    let s = MyStruct;
    s.foo();
    s.baz();
}

さいごに

もしも本リポジトリで不備などあれば、リポジトリのissueやPRなどでご指摘いただければと思います。

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