Rust traits act as generic constraints

Posted 金庆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rust traits act as generic constraints相关的知识,希望对你有一定的参考价值。

Rust traits act as generic constraints

(Jin Qing’s Column, Nov. 18, 2021)

Rust traits are different from interfaces of C++/Java/Go.

See: https://stevedonovan.github.io/rustifications/2018/09/08/common-rust-traits.html

Rust traits are mechanism for adding behavior to types.

Traits have 2 modes. One is interface as Java.

Another is generic constraint. Generic functions are defined over types that implemented specific traits.

The “complie-time duck typing” in C++ templates is avoided in Rust.
Rust will reject a type with quack() method as a Duck type.
We must pass a type which implements Duck trait.
But in Go, a type with quack() method is sufficient to be used as a Duck interface.

以上是关于Rust traits act as generic constraints的主要内容,如果未能解决你的问题,请参考以下文章

rust trait 熟识系列:一日一trait之Seek trait

Rust语言圣经25 - 特征Trait

Rust impl trait

Rust 中 trait 的冲突实现

Rust学习教程25 - 特征Trait

Rust学习教程25 - 特征Trait