Chủ đề Rust quan trọng
Rust Modules and pub
Organize code into modules and decide what the rest of the program may use.
Bạn sẽ học được gì
- mod and pub
- Paths with ::
- use and super
mod geometry
geometrypub circle_areapublicsquareprivatepub mod convertto_degrees
Private unless marked pub
A module groups related functions, types and constants under a name. Everything in a module is private unless it is marked pub, so a module can hide its details.
circle_area is public, but square is private and can only be called inside geometry. Paths use ::, and super refers to the parent module. use brings a name into scope so to_degrees can be called without its full path.
Những điểm quan trọng
- Everything in a module is private by default.
- pub makes an item usable from outside.
- use brings a name into scope.
Ví dụ Rust chạy được
Rust
main.rs
mod geometry {
pub const PI: f64 = 3.14159;
pub fn circle_area(radius: f64) -> f64 {
PI * square(radius)
}
fn square(value: f64) -> f64 {
value * value
}
pub mod convert {
pub fn to_degrees(radians: f64) -> f64 {
radians * 180.0 / super::PI
}
}
}
use geometry::convert::to_degrees;
fn main() {
println!("{:.2}", geometry::circle_area(2.0));
println!("{:.1}", to_degrees(geometry::PI));
}
12.57
180.0Luyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
Tất cả thử thách