- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Declarations in Rust Programming
Use Declarations in Rust are used to bind a full path to a new name. It can be very helpful in cases where the full path is a bit long to write and invoke.
In normal cases, we were used to doing something like this:
use crate::deeply::nested::{ my_function, AndATraitType }; fn main() { my_function(); }
We invoked the use declaration function by the name of the function my_function. Use declaration also allows us to bind the full path to a new name of our choice.
Example
Consider the example shown below:
// Bind the `deeply::nested::function` path to `my_function`. use deeply::nested::function as my_function; fn function() { println!("called `function()`"); } mod deeply { pub mod nested { pub fn function() { println!("called `deeply::nested::function()`"); } } } fn main() { // Easier access to `deeply::nested::function` my_function(); println!("Entering block"); { // This is equivalent to `use deeply::nested::function as function`. // This `function()` will shadow the outer one. use crate::deeply::nested::function; // `use` bindings have a local scope. In this case, the // shadowing of `function()` is only in this block. function(); println!("Exiting block"); } function(); }
Output
called `deeply::nested::function()` Entering block called `deeply::nested::function()` Exiting block called `function()
Advertisements