Supertrait Bounds Demand Base Impls
A supertrait bound makes every Greeter implement Named too, so default methods and generic call sites can call base-trait methods without extra bounds.
Code
trait Named {
fn name(&self) -> &str;
}
// supertrait 约束:实现 Greeter 的类型必须同时实现 Named
trait Greeter: Named {
// 默认方法可以直接调用超 trait 的方法
fn greeting(&self) -> String {
format!("hello, {}", self.name())
}
}
struct City {
title: String,
}
impl Named for City {
fn name(&self) -> &str {
&self.title
}
}
// greeting 不用手写:默认实现借用了 Named::name
impl Greeter for City {}
fn shout<T: Greeter>(item: &T) -> String {
// T: Greeter 隐含 T: Named,name() 在这里也能调用
format!("{} — {}", item.name().to_uppercase(), item.greeting())
}
fn main() {
let city = City { title: "kyoto".into() };
println!("{}", city.greeting());
println!("{}", shout(&city));
}Walking through the code
Read at a glance, it is the functions name, greeting, shout and main, doing all the work.
What to watch for
- No package manager involved: every call lands on a built-in API.
Using it
The main signature looks like: fn name(&self) -> &str;
There are 2 calls inside main — greeting and shout — executed top to bottom.
Key statements
fn shout<T: Greeter>(item: &T) -> String {
// T: Greeter 隐含 T: Named,name() 在这里也能调用
format!("{} — {}", item.name().to_uppercase(), item.greeting())
}
fn greeting(&self) -> String {
format!("hello, {}", self.name())
}
fn name(&self) -> &str {
&self.title
}
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Supertrait Bounds Demand Base Impls?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.