Pybites Logo Rust Platform

From and Into Traits

Easy +2 pts

🎯 Python handles type conversions with constructors and dunder methods:

n = int("42")              # str → int via constructor
f = float(42)              # int → float via constructor

class Celsius:
    def __init__(self, value):
        self.value = value

    def __float__(self):   # supports float(celsius_obj)
        return self.value

Each conversion is ad-hoc. int() works differently from float(), and custom classes define whatever dunder methods they want. There's no single "conversion protocol" that the whole ecosystem agrees on.

Rust has one: the From trait.

The From trait

From<T> defines how to create your type from some other type T:

impl From<(u8, u8, u8)> for Color {
    fn from(rgb: (u8, u8, u8)) -> Self {
        Color { r: rgb.0, g: rgb.1, b: rgb.2 }
    }
}

let red = Color::from((255, 0, 0));

The signature is always the same: fn from(value: T) -> Self. One …

Login to see the full exercise.