Archive/Rust

[Rustlings] 19. macro

rust에서 매크로 기능을 사용하면 복잡한 코드를 간편하게 작성할 수 있다. rust로 프로그램을 작성하면 매크로를 사용하는 모습을 많이 볼 수 있는데 println!이나 vec!가 바로 매크로다.

rust의 매크로는 다양한 모습이 있다.

  • #[derive(Debug)]
  • #![allow(dead_code)]
  • println!("hello");
  • macro_rules! name { () => {}; }

이중에서 macro_rules!을 통해 매크로를 만드는 방법에만 집중한다.

매크로 정의는 rust 코드를 작성하는 방식과 다른 점이 있다. 먼저 매크로 정의는 반드시 매크로 호출보다 먼저 위치해야 한다. 그리고 스코프 밖에서도 해당 매크로를 사용하고 싶다면 #[macro_export]를 붙여줘야 한다.

macro_rules! foo {
  ( $x:expr ) => {
    println!("foo {}", $x);
  };
}

foo!("bar");

macro_rules! 사용법은 https://danielkeep.github.io/tlborm/book/mbe-macro-rules.html을 참고하면 된다.

'Archive > Rust' 카테고리의 다른 글

[Rustlings] 18. thread  (0) 2021.06.12
[Rustlings] 17. Standard Library Types  (0) 2021.06.04
[Rustlings] 16. Testing  (0) 2021.06.01
[Rustlings] 15. trait  (0) 2021.05.31
[Rustlings] 14. Result  (0) 2021.05.30