Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ergonomics: &String does not implement PartialEq<str> #44695

Open
djc opened this Issue Sep 19, 2017 · 1 comment

Comments

Projects
None yet
3 participants
@djc
Copy link
Contributor

djc commented Sep 19, 2017

Start with this:

fn cmp_prefix() -> bool {
    let owned = "foo".to_owned();
    let string_ref = &owned;
    let partial = "foobar";
    string_ref == partial[..3]
}

It doesn't compile: "the trait bound &String: PartialEq<str> is not satisfied".

Let's Google this, first hit is StackOverflow, first/accepted answer talks about .as_ref(), try that. string_ref.as_ref() == &partial[..3] results in "the trait bound &_: PartialEq<str> is not satisfied" [oh, how I hate these underscores in errors].

At this point I try adding * to the LHS or & to the RHS. The latter results in "type annotations required: cannot resolve String: AsRef<_>" [huh?].

Here's actually everything I tried (from my actual code instead of simple example):

meta_subj == db_subj[..998]
&meta_subj == &db_subj[..998]
meta_subj.as_ref() == &db_subj[..998] // I think this was before Googling, even
meta_subj.as_ref() == db_subj[..998]
meta_subj.as_ref::<&str>() == &db_subj[..998] // WTF is this thing with not resolving String: AsRef?
&meta_subj.as_ref() == db_subj[..998]
*meta_subj.as_ref() == db_subj[..998]

At this point I'm pretty much out of ideas other than brute-forcing with some to_string(). I don't really consider myself a beginner at this point, having successfully written a few thousand lines of code over the past 15 months, so here's where I have some empathy for those saying Rust's learning curve is just too steep.

I went and read some more on SO and found this, which actually seems to work (meta_subj as &str) == &db_subj[..998]. The reason I would not have come up with this is that generally the compiler seems to be able to coerce &T where T: String to &str, so I find it hard to come up with a reason it cannot do so in this case.

@kennytm

This comment has been minimized.

Copy link
Member

kennytm commented Sep 19, 2017

FYI this also works.

    *string_ref == partial[..3]

I think #44619 (auto-ref with operators) will fix this.

But even without #44619, the error message could take some idea for the suggestion, rather than telling the user about something they are not able to do anyway (you can't impl PartialEq<str> for &String without hacking the standard library).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.