On Translating Trait

While browsing Zhihu recently, I got into an argument with someone criticizing The Tao of Rust. She considered the book's translation of "trait" as "特型" (texing, roughly "special type") terrible, on a par with the Chinese transliteration of "robustness." I would like to use that discussion as a starting point for sharing my thoughts on traits, in the hope of encouraging further discussion.

I have not read The Tao of Rust. This article is not a review of the book.

The Translation Question

Why does "鲁棒性" (lubangxing, a phonetic rendering of "robustness") attract so much criticism? "Robustness" could have been translated clearly and naturally as "稳健性" (wenjianxing, "stability and resilience"), but the translator chose an opaque transliteration that adds an unnecessary barrier to understanding. Translating "default" as "缺省" (quesheng) has a similar problem. The translation of "trait," by comparison, is much more contentious.

First, should "trait" be translated at all? Opinions differ. In Zhihu answers, comments, and informal essays, keeping the English term seems preferable. But because "trait" is a frequently used technical term, a suitable Chinese expression matters for textbooks and Chinese academic journals.

Second, how should it be translated? The ordinary English word "trait" means a quality, characteristic, or feature. The Rust community tends to use "特征" (tezheng, "characteristic"). To my ear, however, this sounds awkward in phrases such as "higher-ranked trait bounds." I prefer "特质" (tezhi, "quality"), the translation used by the Scala community.

Although the term "trait" came from Scala, Rust's traits are closer to Haskell's type classes. If a type or class abstracts over values or objects, then a trait or interface abstracts over types or classes: a type describes properties shared by a set of values, while a trait describes properties shared by a set of types. Types can therefore constrain variables and function parameters, while traits can constrain generic parameters. In Rust syntax, when the name to the left of : is a variable, the right side specifies its required type; when the name on the left is a generic parameter, the right side specifies the traits it must implement.

This translation helps beginners connect types, generics, and traits. It also makes trait objects easier to understand: a trait object treats a trait as a type, allowing the trait to constrain a variable directly.

Generics

You may already have noticed that a generic parameter resembles a variable or function parameter, except that it stands for a type rather than a value. To distinguish them, we call the former a generic parameter and the latter a value parameter. In the following example, the value parameter v names the supplied value, while the generic parameter T names its type. A call can specify the concrete "value" of T using turbofish syntax:

1
2
3
4
5
6
7
8
fn foo<T: Clone>(v: T) -> T {
    let y = v.clone();
    y
}

fn main() {
    println!("{}", foo::<usize>(128));
}

The call foo::<usize>(128) passes usize to the generic parameter T and 128 to the value parameter v. This is even clearer in Zig:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const std = @import("std");

fn foo(comptime T: type, v: T) T {
    const y = v;
    return y;
}

pub fn main() !void {
    // The two arguments supplied to the call are usize and 128.
    const result = foo(usize, 128);
    std.debug.print("{d}\n", .{result});
}

Zig treats types as first-class citizens and lets them be passed around like values. From this perspective, Zig's syntax is more consistent than Rust's, and its approach to generics is more elegant.

Composition over Inheritance

Inheritance in C++ and Java is inheritance between classes or types: a subclass inherits its parent's data and methods. Rust favors a different abstraction, implementing different traits for a type. This is composition rather than inheritance. Instead of building an "animal" inheritance tree, we implement traits such as making sounds, walking, or flying for types such as cats, dogs, and birds.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// A trait for making sounds.
trait MakesSound {
    fn make_sound(&self) -> String;
}

// A trait for flying.
trait CanFly {
    fn fly(&self);
}

struct Duck;

impl MakesSound for Duck {
    fn make_sound(&self) -> String {
        "quack".to_string()
    }
}

impl CanFly for Duck {
    fn fly(&self) {
        println!("The duck is flying!");
    }
}

struct Car;

// A car cannot fly, but it can honk.
impl MakesSound for Car {
    fn make_sound(&self) -> String {
        "honk".to_string()
    }
}

By composing traits, we can freely add behavior to any type without forcing it into a rigid inheritance hierarchy. A duck can fly and quack; a car can only honk. Modeling this elegantly in an inheritance-based system is difficult. Surely Car should not inherit from Animal?

Composition addresses two classic problems with inheritance:

  1. The fragile base class problem: In a deep inheritance hierarchy, changing an implementation detail in a base class can unexpectedly break the behavior of its subclasses. Trait implementations are attached to types, and the two are loosely coupled, so changes to a trait's default implementation or a specific type's implementation have a more manageable impact.
  2. The diamond problem: Ambiguity arises when a class inherits from two parents that share a base class. If both a scanner and a printer inherit from a USB device, which copy of the USB device's state and behavior should a multifunction device inherit when it extends both? Rust traits avoid this problem at its root: traits define behavior without storing data or state, so a type can implement any number of traits without this conflict.

Traits also provide default implementations. These let us share code across types, gaining some of the benefits of inheritance while retaining the flexibility of composition.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
trait Greet {
    // A method with a default implementation.
    fn greet(&self) {
        println!("Hello!");
    }
}

struct Person;
impl Greet for Person {} // Use the default implementation.

struct Robot;
impl Greet for Robot {
    // The default implementation can also be overridden.
    fn greet(&self) {
        println!("01001000 01100101 01101100 01101100 01101111 00100001");
    }
}

Conclusion

The key to understanding traits is to connect them with types, value parameters, and generic parameters, and to consider both "types of types" and "combinations of behavior." The next time you see : in Rust code, consider the relationship between its two sides. Whether it is variable: type or Generics: Trait, it expresses a constraint and a relationship of belonging. That is part of the appeal of a type system.

Refresh