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

Implement From<T> for enums where T: AsRef<str> #87

Open
46ki75 opened this issue Nov 28, 2024 · 0 comments
Open

Implement From<T> for enums where T: AsRef<str> #87

46ki75 opened this issue Nov 28, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@46ki75
Copy link
Owner

46ki75 commented Nov 28, 2024

Description

Currently, converting a string-like value (e.g., String, &str) into an enum requires either manual matching or custom implementations in each use case. To enhance usability and provide a consistent conversion mechanism, I propose implementing From<T> for enums where T: AsRef<str>.

Motivation

  • Improved Developer Experience: This enhancement will allow developers to seamlessly convert string-like values into enum variants using the .into() method.
  • Flexibility: By utilizing T: AsRef<str>, the implementation will support multiple input types (String, &str, etc.) without duplicating code.
  • Standardization: It will encourage a consistent approach to enum conversion, reducing boilerplate code and improving maintainability.

Proposed Solution

  1. Implement the From<T> trait for enums using the AsRef<str> constraint.
  2. Provide a default matching mechanism that maps specific strings to enum variants.
  3. For unsupported strings, the implementation should either:
    • (Option A) Panic with a clear error message (if using From).
    • (Option B) Return a Result<Self, Error> (if using TryFrom, which supports error handling).

Example

With From<T>:

#[derive(Debug)]
enum MyEnum {
    VariantA,
    VariantB,
    VariantC,
}

impl<T> From<T> for MyEnum
where
    T: AsRef<str>,
{
    fn from(value: T) -> Self {
        match value.as_ref() {
            "VariantA" => MyEnum::VariantA,
            "VariantB" => MyEnum::VariantB,
            "VariantC" => MyEnum::VariantC,
            _ => panic!("Invalid value for MyEnum"),
        }
    }
}

Usage:

let value: MyEnum = "VariantA".into();
println!("{:?}", value); // Output: VariantA

With TryFrom<T> (for safer conversion):

use std::convert::TryFrom;

impl<T> TryFrom<T> for MyEnum
where
    T: AsRef<str>,
{
    type Error = &'static str;

    fn try_from(value: T) -> Result<Self, Self::Error> {
        match value.as_ref() {
            "VariantA" => Ok(MyEnum::VariantA),
            "VariantB" => Ok(MyEnum::VariantB),
            "VariantC" => Ok(MyEnum::VariantC),
            _ => Err("Invalid value for MyEnum"),
        }
    }
}

Usage:

let result: Result<MyEnum, _> = MyEnum::try_from("VariantA");
match result {
    Ok(value) => println!("Converted: {:?}", value),
    Err(e) => println!("Error: {}", e),
}

Impact

This implementation will significantly simplify the process of converting strings into enums, especially in projects where enums are frequently used for configuration or input validation.

Open Questions

  • Should the default implementation use From (panic on invalid input) or TryFrom (return an error)?
  • Should this feature include a macro for generating implementations across multiple enums?
@46ki75 46ki75 added the enhancement New feature or request label Nov 28, 2024
@46ki75 46ki75 self-assigned this Nov 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant