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

How to Properly Use FromStr? #262

Open
JimLynchCodes opened this issue Apr 3, 2023 · 1 comment
Open

How to Properly Use FromStr? #262

JimLynchCodes opened this issue Apr 3, 2023 · 1 comment

Comments

@JimLynchCodes
Copy link

JimLynchCodes commented Apr 3, 2023

Hi, sorry if this is a dumb question, but I find the giant comment code block in the strum docs to be very confusing...

What does the comment mean by "generated code"? Generated from what? Am I supposed to copy-paste this code somewhere? What is the point of showing this in the docs?

Also, in the docs is says FromStr is "autoderived", but I am getting an error that it's not found...

Here is my enum:

use strum_macros::EnumString;
use std::str::FromStr;

#[derive(Debug, PartialEq, EnumString)]
pub enum PizzaSize {

    #[strum(ascii_case_insensitive, serialize = "s")]
    Small,
}

I then try to get a variable of my small variant from a string:

let size = PizzaSize::from_str(&ans).unwrap();

But it gives me this compiler error:

error[E0599]: no variant or associated item named `from_str` found for enum `PizzaSize` in the current scope
  --> src/bin/pizza_ordering/prompt_coordinator.rs:25:31
   |
25 |         Some(s) => PizzaSize::from_str(s).unwrap(),
   |                               ^^^^^^^^ variant or associated item not found in `PizzaSize`
   |
  ::: src/bin/pizza_ordering/types.rs:5:1
   |
5  | pub enum PizzaSize {
   | ------------------ variant or associated item `from_str` not found for this enum
   |

What?? I thought it was auto-derived!!?

Do I need to manually add this from_str function with an impl block? Or somehow explicitly tell it to derive FromStr in addition to the derive macros I'm already using? 🤔

Thanks!

@PokeJofeJr4th
Copy link
Contributor

You don't need to import the trait for the derive macro to work, so you can remove the use std::str::FromStr; line from the types file unless you need it there for a different reason. In order to use a trait method like from_str(&str), the corresponding trait needs to be in scope, so you need to add the use std::str::FromStr; line to the prompt coordinator file.

I highly recommend using cargo clippy for problems like this, since it almost always provides really good solutions and helps you understand what's going on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants