Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

use 宣言

use 宣言は、アクセスを容易にするために、フルパスを新しい名前にバインドするために使用できます。多くの場合、次のように使用されます。

use crate::deeply::nested::{
    my_first_function,
    my_second_function,
    AndATraitType
};

fn main() {
    my_first_function();
}

as キーワードを使用して、インポートを別の名前にバインドできます。

// `deeply::nested::function` パスを `other_function` にバインドします。
use deeply::nested::function as other_function;

fn function() {
    println!("called `function()`");
}

mod deeply {
    pub mod nested {
        pub fn function() {
            println!("called `deeply::nested::function()`");
        }
    }
}

fn main() {
    // `deeply::nested::function` へより簡単にアクセス
    other_function();

    println!("Entering block");
    {
        // これは `use deeply::nested::function as function` と同等です。
        // この `function()` は外側のものをシャドーイングします。
        use crate::deeply::nested::function;

        // `use` バインディングはローカルスコープを持ちます。この場合、
        // `function()` のシャドーイングはこのブロック内だけです。
        function();

        println!("Leaving block");
    }

    function();
}

pub use を使用して、モジュールから項目を再エクスポートすることもできます。これにより、その項目にはモジュールの公開インターフェースを通じてアクセスできます。

mod deeply {
    pub mod nested {
        pub fn function() {
            println!("called `deeply::nested::function()`");
        }
    }
}

mod cool {
    pub use crate::deeply::nested::function;
}

fn main() {
    cool::function();
}