Zum Inhalt springen

Module

pub mod a {
pub mod b {
pub fn f() { println!("b1"); }
pub mod c {
pub fn f() { println!("c1"); }
}
}
pub fn entry() { super::b::c::f(); }
}
pub mod b {
pub fn f() { println!("b2"); }
pub mod c {
pub fn f() { println!("c2"); }
}
}
fn main() {
crate::a::entry();
}

entry verwendet den Pfad super::b::c::f . entry befindet sich im Modul a , daher bezieht sich super auf das übergeordnete Modul von a , welches das Root-Crate ist. Das Kind b des Roots ist dann das äußerste Modul b , dessen Kind c eine Funktion f enthält, die "c2" ausgibt.


pub mod point {
#[derive(Debug)]
pub struct Point(i32, i32);
impl Point {
pub fn origin() -> Self { Point(0, 0) }
}
}
fn main() {
let mut p = point::Point::origin();
p.0 += 1;
println!("{p:?}");
}

Obwohl die Point -Struktur und die statische Methode origin beide öffentlich sind, ist das Feld i32 nicht als pub markiert. Daher ist der direkte Zugriff auf p.0 außerhalb des point -Moduls nicht erlaubt. Dieses Programm würde kompilieren, wenn Zeile 3 in pub struct Point(pub i32, pub i32) geändert würde.