Created
December 2, 2022 14:40
-
-
Save usagi/d37d79d2a980d544f8d50ee03b078af8 to your computer and use it in GitHub Desktop.
> RustのprocmacroでFizzBuzzする実装ってどう書けば良いかな?
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 proc_macro::TokenStream; | |
use proc_macro2::Span; | |
use quote::quote; | |
use syn::{parse_macro_input, parse_quote, Expr}; | |
// `fizzbuzz`マクロを定義する | |
#[proc_macro] | |
pub fn fizzbuzz(input: TokenStream) -> TokenStream { | |
// 引数をパースする | |
let input = parse_macro_input!(input as Expr); | |
// 引数を評価して、整数値を取得する | |
let value = match input { | |
Expr::Lit(lit) => match lit.lit { | |
// 整数リテラルの場合 | |
syn::Lit::Int(int) => int.value(), | |
// それ以外の場合 | |
_ => panic!("expected an integer literal"), | |
}, | |
// それ以外の場合 | |
_ => panic!("expected an integer literal"), | |
}; | |
// 3で割り切れるか、5で割り切れるか、両方で割り切れるかを判定する | |
let output = if value % 15 == 0 { | |
// 両方で割り切れる場合 | |
quote!("FizzBuzz") | |
} else if value % 3 == 0 { | |
// 3で割り切れる場合 | |
quote!("Fizz") | |
} else if value % 5 == 0 { | |
// 5で割り切れる場合 | |
quote!("Buzz") | |
} else { | |
// 両方で割り切れない場合 | |
parse_quote!(#value) | |
}; | |
// 結果を返す | |
TokenStream::from(output) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment