-
-
Save rust-play/ec4918ad4ba8f00c885c39678bffd704 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::str::FromStr; | |
use std::{fmt::Debug, marker::PhantomData}; | |
struct Wrap<T>(std::marker::PhantomData<T>); | |
trait ViaParseDebug<'a, T> { | |
fn magic_conversion(&self, input: &'a str) -> T; | |
} | |
impl<'a, T> ViaParseDebug<'a, T> for &&Wrap<T> | |
where | |
T: FromStr, | |
T::Err: Debug, | |
{ | |
fn magic_conversion(&self, input: &'a str) -> T { | |
T::from_str(input).unwrap() | |
} | |
} | |
trait ViaParse<'a, T> { | |
fn magic_conversion(&self, input: &'a str) -> T; | |
} | |
impl<'a, T> ViaParse<'a, T> for &Wrap<T> | |
where | |
T: FromStr, | |
{ | |
fn magic_conversion(&self, input: &'a str) -> T { | |
match T::from_str(input) { | |
Ok(v) => v, | |
Err(_) => { | |
panic!("Cannot parse '{}' to get T", input); | |
} | |
} | |
} | |
} | |
trait ViaIdent<'a, T> { | |
fn magic_conversion(&self, input: &'a str) -> T; | |
} | |
impl<'a> ViaIdent<'a, &'a str> for &&Wrap<&'a str> { | |
fn magic_conversion(&self, input: &'a str) -> &'a str { | |
input | |
} | |
} | |
#[derive(Debug)] | |
struct S; | |
impl FromStr for S { | |
type Err = (); | |
fn from_str(_s: &str) -> Result<Self, Self::Err> { | |
Ok(S) | |
} | |
} | |
#[derive(Debug)] | |
struct ErrorNotImplementDebug; | |
struct ErrorWithoutDebug; | |
impl FromStr for ErrorNotImplementDebug { | |
type Err = ErrorWithoutDebug; | |
fn from_str(s: &str) -> Result<Self, Self::Err> { | |
match s { | |
"error" => Err(ErrorWithoutDebug), | |
_ => Ok(ErrorNotImplementDebug), | |
} | |
} | |
} | |
#[allow(dead_code)] | |
struct NotImplementFromStr; | |
type StrTypeAlias = &'static str; | |
fn main() { | |
let u = (&&&Wrap::<u32>(PhantomData)).magic_conversion("42"); | |
println!("{}", u); | |
let s = (&&&Wrap::<&str>(PhantomData)).magic_conversion("hi"); | |
println!("{}", s); | |
let str_type_alias = (&&&Wrap::<StrTypeAlias>(PhantomData)).magic_conversion("alias"); | |
println!("{}", str_type_alias); | |
let parse_without_error = | |
(&&&Wrap::<ErrorNotImplementDebug>(PhantomData)).magic_conversion("42"); | |
println!("{:?}", parse_without_error); | |
let _parse_without_error = | |
(&&&Wrap::<ErrorNotImplementDebug>(PhantomData)).magic_conversion("error"); | |
//let not_implement: NotImplementFromStr = (&&&Wrap::<NotImplementFromStr>(PhantomData)).magic_conversion("42"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment