Skip to content

Suggest implementing TryFrom<&str> for types implementing FromStr #5588

Open
@Luro02

Description

@Luro02

It is not much work to implement TryFrom<&str> for types implementing FromStr, you can even generalize it;

impl<T> TryFrom<&str> for T
where
    T: FromStr
{
    type Error = T::Err;

    fn try_from(input: &str) -> Result<Self, Self::Error> {
        Self::from_str(input)
    }
}

I don't think there is much of a reason to not implement it.

You might even be able to provide a more efficient implementation:

struct Hello<'a>(Cow<'a, str>);

impl FromStr for Hello<'static> {
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Ok(Self(Cow::Owned(input.into())))
    }
}

impl<'a> TryFrom<&'a str> for Hello<'a> {
    fn try_from(input: &'a str) -> Result<Self, Self::Error> {
        Ok(Self(Cow::Borrowed(input)))
   }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.L-styleLint: Belongs in the style lint group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions