3 ms·
Another wart (in a separate post from my other wart so that replies are coherent): I understand why &str and String are different, but why do they act like the
by rspeer 10y ago
Another wart (in a separate post from my other wart so that replies are coherent):
I understand why &str and String are different, but why do they act like they've never heard of each other? Why do they implement such different sets of methods? Why can't they be compared for equality, so I don't always have to type "literal".to_string()?
Haskell has problems with too many string types as well (worse than Rust, because the type of their default string literals is best avoided entirely), but they fix much of the problem with the OverloadedStrings extension, which uses the type checker as something that helps you coerce string literals, instead of arguing with you.
- steveklabnik 10y ago> 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 ==.
- rspeer 10y agoI 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()?
- dbaupp 10y agoString == &str works. Maybe you were encountering some other problem.
- rspeer 10y agoOh, 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.
- bbatha 10y agoYou can do: foo() -> Option<String> foo().as_ref() == Some("str")
- comex 10y agoNitpick: 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.
- tatterdemalion 10y ago> 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.
- steveklabnik 10y agoWorks just fine here: https://play.rust-lang.org/?gist=5a3228a1d42d81690458337eb77b9caf&version=stable&backtrace=0 https://play.rust-lang.org/?gist=5a3228a1d42d81690458337eb77... Maybe you were running into something else?