トレイトが何らの機能を持っていなくとも境界条件として使えるというサンプルコードです。
https://doc.rust-jp.rs/rust-by-example-ja/generics/bounds/testcase_empty.html
のコードにYellowトレイトを追加しています。
struct Cardinal;
struct BlueJay;
struct Turkey;
trait Red {}
trait Blue {}
trait Yellow {}
impl Red for Cardinal {}
impl Blue for BlueJay {}
impl Yellow for Turkey {}
// These functions are only valid for types which implement these
// traits. The fact that the traits are empty is irrelevant.
fn red<T: Red>(_: &T) -> &'static str { "red" }
fn blue<T: Blue>(_: &T) -> &'static str { "blue" }
fn yellow<T: Yellow>(_: &T) -> &'static str { "yellow" }
fn main() {
let cardinal = Cardinal;
let blue_jay = BlueJay;
let turkey = Turkey;
// `red()` won't work on a blue jay nor vice versa
// because of the bounds.
println!("A cardinal is {}", red(&cardinal));
println!("A blue jay is {}", blue(&blue_jay));
println!("A turkey is {}", yellow(&turkey));
}
このソースではライフタイム指定(‘static)はしなくとも動作します。
admin