Gatonito
Gatonito

Reputation: 2164

How to use impl<'a> From<&'a Method> for &'a str in Rust?

There's this trait implementation for an enum Method which is self explanatory:

impl<'a> From<&'a Method> for &'a str {
    fn from(v: &'a Method) -> Self {
        match v {
            Method::Describe => "DESCRIBE",
            Method::GetParameter => "GET_PARAMETER",
            Method::Options => "OPTIONS",
            Method::Pause => "PAUSE",
            Method::Play => "PLAY",
            Method::PlayNotify => "PLAY_NOTIFY",
            Method::Redirect => "REDIRECT",
            Method::Setup => "SETUP",
            Method::SetParameter => "SET_PARAMETER",
            Method::Teardown => "TEARDOWN",
            Method::Extension(ref v) => v,
        }
    }
}

Given let a = Method::Describe, how can I generate a String from it?

let x: String = a.into()

won't work because into() works only for str.

I found this to work:

let s: &str = request.method().into();
let x: String = s.into();

Can I do however do everything in one line?

Upvotes: 1

Views: 215

Answers (1)

lpiepiora
lpiepiora

Reputation: 13749

I think you can do it like so:

let x: String = From::<&str>::from(a.into());
let y: String = Into::<&str>::into(a).to_owned();

Or you can define a new From implementation for String:

impl<'a> From<&'a Method> for String {
    fn from(x: &'a Method) -> Self {
        let x: &str = x.into();
        x.to_owned()
    }
}

Then you can call it like this: let z: String = a.into()

Upvotes: 2

Related Questions