Skip to content

Method as_ref not suggested when it should #55198

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

Closed
KillTheMule opened this issue Oct 19, 2018 · 1 comment
Closed

Method as_ref not suggested when it should #55198

KillTheMule opened this issue Oct 19, 2018 · 1 comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints

Comments

@KillTheMule
Copy link
Contributor

KillTheMule commented Oct 19, 2018

As per https://www.reddit.com/r/rust/comments/9pb3ah/what_cool_stuff_have_you_learned_about_rust/e80zqpc/, I'm reporting a case where the method as_ref is not suggested by the compiler to use to convert an &Option<T> to an Option<&T>. Here's a playground link, the non-working code is

pub struct Keyword {}

pub struct ParsedLine<'a> {
  pub keyword: Option<&'a Keyword>,
}

impl<'a> From<&'a Option<Keyword>> for ParsedLine<'a>
{
  fn from(k: &'a Option<Keyword>) -> ParsedLine<'a>
  {
      ParsedLine{keyword: k}
  }
}
error[E0308]: mismatched types
  --> src/main.rs:13:27
   |
13 |       ParsedLine{keyword: k}
   |                           ^ expected enum `std::option::Option`, found reference
   |
   = note: expected type `std::option::Option<&Keyword>`
              found type `&'a std::option::Option<Keyword>`

The playground is using stable, I'm seeing this behavior on rustc 1.31.0-nightly (de3d640f5 2018-10-01) as well locally. If I should provide more information, let me know :)

@Havvy Havvy added the A-diagnostics Area: Messages for errors, warnings, and lints label Oct 19, 2018
@estebank
Copy link
Contributor

For both Result (if appropriate) and Option it should suggest using as_ref():

error[E0308]: mismatched types
  --> src/main.rs:13:27
   |
13 |       ParsedLine{keyword: k}
   |                           ^
   |                           |
   |                           expected enum `std::option::Option`, found reference
   |                           help: use `as_ref` here: `k.as_ref()`
   |
   = note: expected type `std::option::Option<&Keyword>`
              found type `&'a std::option::Option<Keyword>`

bors added a commit that referenced this issue Dec 30, 2018
Suggest `.as_ref()` when appropriate for `Option` and `Result`

Fix #55198.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints
Projects
None yet
Development

No branches or pull requests

3 participants