测试实例:空限定

限定的工作机制有一个效果是,即使一个 trait 不包含任何功能,你仍然可以使用它作为一个限定。在标准库中的 Eq 和 Ord 就是这样的例子。

1. struct Cardinal;
2. struct BlueJay;
3. struct Turkey;

5. trait Red {}
6. trait Blue {}

8. impl Red for Cardinal {}
9. impl Blue for BlueJay {}

11. // 这些函数只对实现了相应的 trait 的类型有效。实际情况中 trait 内部
12. // 是否为空都无所谓。
13. fn red<T: Red>(_: &T)   -> &'static str { "red" }
14. fn blue<T: Blue>(_: &T) -> &'static str { "blue" }

16. fn main() {
17. let cardinal = Cardinal;
18. let blue_jay = BlueJay;
19. let _turkey   = Turkey;

21. // 由于限定,`red()` 不能调用 blue_jay (蓝松鸟),
22. // 反过来也一样。
23. println!("A cardinal is {}", red(&cardinal));
24. println!("A blue jay is {}", blue(&blue_jay));
25. //println!("A turkey is {}", red(&_turkey));
26. // ^ 试一试:将此行注释去掉。
27. }

参见:

std:![:cmp:](https://www.emoji-cheat-sheet.com/graphics/emojis/cmp.png ":cmp:"):Eq, std:![:cmp:](https://www.emoji-cheat-sheet.com/graphics/emojis/cmp.png ":cmp:"):Ord, 和 trait