Why no deref needed for String and deref is mandatory for Box type?

fn main(){
    let a = Box::new(10);  
    assert_eq!(10, a); //This wont work
   // assert_eq!(10, *a); //This will work

    let c = String::from("hai");

    assert_eq!("hai", c);  // this will work


The string comparison works because impl<'a> PartialEq<String> for &'a str exists.

If it didn't, then you would need to first convert the String into a &str before you could compare them.


What is comparable through box/reference is a bit ad-hoc in Rust.

fn main() {
    let boxed: Box<str> = "nope".into();
    assert_eq!(boxed, "nope"); // this doesn't work either

    assert_eq!(*boxed, "nope"); // still wrong

    assert_eq!(&*boxed, "nope"); // that works
1 Like