iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💬

[Rust] Trait Bounds: The Basics

に公開

Trait Bounds

A feature that guarantees at compile-time that a specific type implements a specific trait.

The Compiler Points Out Type Mismatches

Generics are a way to represent types ambiguously. Specifying them ambiguously is effective in some situations.
For example, here is a situation where you might think, "Regardless of the type, I want to add them if they are numbers."

fn add_values<T>(a: T, b: T) -> T {
    a + b
}

fn main() {
    let sum = add_values(5, 10);
    println!("Sum: {}", sum);
}

However, this results in an error:

error[E0369]: cannot add `T` to `T`
 --> src/main.rs:2:9
  |
2 |     a + b
  |     - ^ - T
  |     |
  |     T
  |
  = note: no implementation for `T + T`
  = help: the trait `std::ops::Add` is not implemented for `T`

According to the compiler, "To use the + operator, the type T must implement the Add trait."

Let's Explicitly Define the Behavior

Use std::ops::Add to explicitly indicate to the compiler that you want to perform addition.
Also, with T: Add<Output = T>, you need to specify what the resulting type of the addition should be. In this case, it is the same type as the values being added.

use std::ops::Add;

fn add_values<T>(a: T, b: T) -> T
where
    T: Add<Output = T>,
{
    a + b
}

fn main() {
    let sum_int = add_values(5, 10);       // i32 type
    println!("Sum (int): {}", sum_int);

    let sum_float = add_values(3.5, 2.7);  // f64 type
    println!("Sum (float): {}", sum_float);
}

Summary

By using trait bounds, you can guarantee at compile time that a generic type implements the necessary traits (in this case, Add). This provides the following benefits:

Improved Type Safety: Prevents the accidental use of types that do not support the required operations.
Early Error Detection: Issues can be detected at compile time, reducing runtime bugs.
Code Versatility: By appropriately specifying trait bounds, you can create generic functions and structs for various types.

Of course, they can be used in scenarios other than dealing with generic types. I plan to write another article about that in the future.


https://doc.rust-jp.rs/book-ja/ch10-02-traits.html

Discussion