Github impl FromStr for proc_macro::Literal by dtolnay · Pull Request #84717 · r...
source link: https://github.com/rust-lang/rust/pull/84717
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Conversation
Note that unlike impl FromStr for proc_macro::TokenStream
, this impl does not permit whitespace or comments. The input string must consist of nothing but your literal.
-
"1".parse::<Literal>()
⟶ ok -
"1.0".parse::<Literal>()
⟶ ok -
"'a'".parse::<Literal>()
⟶ ok -
"\"\n\"".parse::<Literal>()
⟶ ok -
"0 1".parse::<Literal>()
⟶ LexError -
" 0".parse::<Literal>()
⟶ LexError -
"0 ".parse::<Literal>()
⟶ LexError -
"/* comment */0".parse::<Literal>()
⟶ LexError -
"0/* comment */".parse::<Literal>()
⟶ LexError -
"0// comment".parse::<Literal>()
⟶ LexError
Use case
let hex_int: Literal = format!("0x{:x}", int).parse().unwrap();
The only way this is expressible in the current API is significantly worse.
let hex_int = match format!("0x{:x}", int) .parse::<TokenStream>() .unwrap() .into_iter() .next() .unwrap() { TokenTree::Literal(literal) => literal, _ => unreachable!(), };
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK