use
- Rust course
- Intermediate
- Lesson 72/115
- 4 min
Bring module names into scope with use.
use
use brings a path into scope to shorten long names. The convention: for functions bring in the parent module, for types bring in the type itself:
use std::collections::HashMap; // type: itself
use sekil::kare; // function: parent module
let m: HashMap<&str, i32> = HashMap::new();
let a = kare::alan(3.0); // its origin is clearOn a name clash, rename with as: use sekil::daire::alan as daire_alan;.
Nested paths
Several items from the same root can be taken in one line:
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::{self, Display};
mod sekil {
pub mod daire {
pub fn alan(r: f64) -> f64 { std::f64::consts::PI * r * r }
}
pub mod kare {
pub fn alan(a: f64) -> f64 { a * a }
}
}A use declaration is only valid in the scope where it's written; if it's needed inside a module, it must be written there too.
Practice Short paths
Write the sekil module tree above. use daire::alan under the name daire_alan and the kare module under its own name. Print the results of daire_alan(1.0) and kare::alan(3.0) with {:.2}, separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
mod sekil {
pub mod daire {
pub fn alan(r: f64) -> f64 {
std::f64::consts::PI * r * r
}
}
pub mod kare {
pub fn alan(a: f64) -> f64 {
a * a
}
}
}
use sekil::daire::alan as daire_alan;
use sekil::kare;
fn main() {
println!("{:.2} {:.2}", daire_alan(1.0), kare::alan(3.0));
}Expected output
3.14 9.00
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>use std::io::{self, Write};</code> bring into scope?
- It doesn't compile
- The io module and the Write trait Correct answer
- Only Write
- Everything in io
Explanation: Braces combine several paths; self is that module itself. To take everything, io::* is written (a glob), but it's generally discouraged.
2 Rename
use sekil::daire::alan ____ daire_alan;
use sekil::daire::alan as daire_alan;
Explanation: as gives the imported item a new name.
3 use declaration and effect
| Term | Meaning |
|---|---|
use sekil::kare; |
Write kare::alan |
use sekil::daire::alan as daire_alan; |
daire_alan(..) |
use std::io::{self, Write}; |
io and Write |
use std::io::*; |
Glob import |