Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Why do they implement such different sets of methods?

String gets all relevant str methods from Deref; it has some additional methods, but it should largely be shared.

> Why can't they be compared for equality,

Hm? They both compare just fine with ==.



I mean, if I have a method foo() that returns a String, as many methods do, why can't I check if foo() == "bar"? Why do I have to check foo() == "bar".to_string()?


Works just fine here: https://play.rust-lang.org/?gist=5a3228a1d42d81690458337eb77...

Maybe you were running into something else?


String == &str works. Maybe you were encountering some other problem.


Oh, I guess the case of this I encountered most recently was actually Option<String> == Option<&str>.

I get why that's different, but it would be great if the type system could figure that out, so that the literal Some("foo") could be an Option<String> if necessary. Maybe I'm still being spoiled by Haskell's OverloadedStrings.


Nitpick: if you have a String and a &str, you want to convert the first to the second, not the other way around. Strings are owned, so &str to String does an allocation and copy of the bytes, while String to &str is a trivial operation that just throws away the capacity field.

But yeah, it would be nice if Rust had better ergonomics regarding coercing the insides of wrapper types. Though I'm not sure how exactly that would work.


You can do:

  foo() -> Option<String>

  foo().as_ref() == Some("str")


> Oh, I guess the case of this I encountered most recently was actually Option<String> == Option<&str>.

There are pretty rough type inference issues preventing this impl from existing. Too many people are doing `opt == None` & the compiler would no longer be able to infer the type of None. (You should not be one of them, just call `is_none()` instead)

I'd like to see this impl some day but its not clear how to make it happen.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: