Traits for implicit coercion

⚓ rust    📅 2025-06-16    👤 surdeus    👁️ 3      

surdeus

I am to learn syntax... and typing .into() seems that I am missing some knowledge on Rust's way of code.

#[derive(Debug)]
pub struct A(isize);

impl From<isize> for A {
    fn from(value: isize) -> Self {
        A(value)
    }
}

#[derive(Debug)]
pub struct B(isize);

// impl something here

fn main() {
    let a: A = 32.into();
    println!("A={:?}({})", a, a.0);
    
    let b: B = 32; // so this is legal.
    println!("B={:?}({})", b, b.0);
}

Is assigning b:B to 32 directly somehow possible?

2 posts - 2 participants

Read full topic

🏷️ rust_feed