Below you will find pages that utilize the taxonomy term “Rust”
August 21, 2025
Something about rust compiler
Names of associated items
类方法、类中 associated const item 都属于 value namespace. 但是由于一个 struct 可以有多个 impl 块,仍然会有重名发生.
enum D {
A,
B,
C,
}
impl Int for D {
const FN: i32 = 1926;
fn get(&self) -> i32 {
match self {
D::A => 1,
D::B => 2,
D::C => 3,
}
}
}
impl Str for D {
fn get(&self) -> String {
match self {
D::A => String::from("A"),
D::B => String::from("B"),
D::C => String::from("C"),
}
}
}
impl D {
fn get(&self) -> i32 {
114514
}
}
impl Con for D {}
struct P {}
impl Int for P {
const FN: i32 = 2026;
fn get(&self) -> i32 {
1919810
}
}
trait Int {
const FN: i32;
fn get(&self) -> i32;
}
trait Str {
fn get(&self) -> String;
}
trait Con {
const FN: i32 = 0817;
}
struct Y {
i: i32,
p: i32,
}
fn g(d: i32, ff: &str) -> [i32; 2] {
let mut a = [0; 2];
a[0] = d;
a[1] = ff.len() as i32;
a
}
fn main() {
let d = D::B;
println!("{}", D::get(&d)); // 114514
println!("{}", Int::get(&d)); // 2
let p = P {};
println!("{}", Int::get(&p)); // 1919810
println!("{}", Str::get(&d)); // B
println!("{}", d.get()); // 114514
println!("{}", P::FN); // 2026
// println!("{}", D::FN); // error
// println!("{}", Int::FN); // error
// println!("{}", Con::FN); // error
println!("{}", <D as Con>::FN); // 817
println!("{}", <D as Int>::FN); // 1926
println!(
"{:?}",
g({ 123 }, "Hello") // [123, 5]
);
}
总之 1.field 和 method 可以重名;2.默认用 inherent impl 的 associated item, 它会覆盖 trait impl 的同名 item;3.如果要用 trait impl 的同名 item, 需要显式指定 trait 名.