Help in this type coercion (I don’t know how title this properly)

⚓ Rust    📅 2025-11-18    👤 surdeus    👁️ 11      

surdeus

Sorry if I am being incompetent;

let a = String::from(“aaa”) ;
let b: &str = &a;

Here this is “tried” simple-reference-coercion example but with custom types

 struct A {
    a: u32,
}

impl core::convert::AsRef<u8> for A {
    fn as_ref(&self) -> &u8 {
        &5
    }
}
fn main() {
    let a: A = A {a: 5};
    let b: &u8 = &a;
}

This errors, I predict you suggest by simply change the line with “let b: &u8 = &a” into “let b: &u8 = a.as_ref()”
But I want is that is there a trait that; without need of using method onto custom type (without b.as_ref(), etc) that can implicitly coerce 1 reference of custom type to another reference custom type or is there no such thing as applies to compiler’s primitive types like references of a string coerces into str without need of method onto.

Also if it does; in

does the “coercion” of custom types work when the custom type is in argument of a function or method in his example or is it compiler monomorphisation

3 posts - 3 participants

Read full topic

🏷️ Rust_feed