Surprising destructuring behavior

⚓ Rust    📅 2025-08-22    👤 surdeus    👁️ 4      

surdeus

Given that i32 implements Copy, I was expecting x2 to be an i32 like x1 instead of &i32. What is the special rule which governs this case?

struct Foo {
    value: i32,
}

fn get_var_type<T>(_var: &T) -> &'static str {
    std::any::type_name::<T>()
}

fn main() {
    let f = Foo { value: 1 };
    let rf = &f;

    let x1 = rf.value;
    println!("x1 has type {}", get_var_type(&x1));

    let Foo { value: x2 } = rf;
    println!("x2 has type {}", get_var_type(&x2));
}

(Playground)

Output:

x1 has type i32
x2 has type &i32

4 posts - 3 participants

Read full topic

🏷️ Rust_feed