Why &str == Box<str> not working?

fn main() {
    let s: Box<str> = "aaa".into();
    if s == "aaa" {
        println!("all good");
    }
}

cause compilation error, plus rustc compiler gives wrong suggestion:

help: call `Into::into` on this expression to convert `&'static str` into `Box<str>`
   |
12 |     if s == "aaa".into() {
   |                  +++++++

I can fix code by &*s == "aaa", but I wonder why there is no something like Derefnot implemented forBox, that automatically convert it to &strorPartialEqto compare with&str` ?

Hm, when I changed the code as the compiler suggested, it compiled. It seems to be a valid suggestion. Do you mean it is not your preferred suggestion?

Box implements Deref. Otherwise you couldn't do your &*s reborrowing solution. Deref-coercion doesn't kick in here (even when we do &s == "aaa"), because the argument of an if statement is not a coercion site, I think. let statements are coercion sites and this works:

fn main() {
    let s: Box<str> = "aaa".into();
    let s: &str = &s;
    
    if s == "aaa" {
        println!("all good");
    }
}

Playground.

2 Likes

Allocation of memory is not cheap, especially when you can not avoid any allocations.
And "aaa".into() is actually allocate memory.

1 Like

Oh, you're right! I was confused and thought it did not allocate in this case, thanks.

Box<str> is missing a lot of implementations. Dereferencing it to &str helps:

    if &*s == "aaa" {

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.