0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Rust] マクロを書く 1st step

Last updated at Posted at 2024-10-30

rustにマクロ定義の機能があるので、それを使ってマクロを書きます。

サンプルプログラムは、エラトステネスの篩で、素数を求めるプログラムです。

pops(l)というマクロです。ベクターlからpopして、Noneだった場合は1を返します。

マクロ

macro.rs
#[macro_export]
macro_rules! pops {
    ($vec:ident) => {
        match $vec.pop() {
            Some(value) => value,
            None => 1,
        }
    };
}

ソース

sieve.rs
use std::env;
mod macro;   // マクロファイルをインクルードする

fn main() {
    let args: Vec<String> = env::args().collect();
    let n=&args[1];
    let n:i32=n.parse().unwrap();
    let f:Vec <i32>=sieve(n);
    let l:i32=f.len() as i32;
    println! ("{:?} : {:?} ",l,f);
}

fn sieve(n:i32)->Vec<i32> {
  let mut tab:Vec<i32>=(2..=n).rev().collect();
  let mut l:Vec<i32>=vec![];
  while !tab.is_empty() {
    let v:i32=pops!(tab);  //ここでマクロを使っている。
    l.push(v);
    tab.retain(|&x| x%v !=0);
    }
  l
}

簡単な構成なので、cargoを使う必要がありません。

コンパイル:rustc sieve.rs
実行:./sieve 100

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?