Peternator7 / strum

A small rust library for adding custom derives to enums
https://crates.io/crates/strum
MIT License
1.8k stars 152 forks source link

How to Properly Use FromStr? #262

Open JimLynchCodes opened 1 year ago

JimLynchCodes commented 1 year ago

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 commented 1 year ago

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.