CodeBlanks Logo Icon CodeBlanks

Types

Write macros with type parameters like $ty:ty.

Fragment types

The fragment type says which code piece the macro expects:

$x:expr     // expression: 1 + 2, f(x)
$x:ident    // identifier: ad, Kutu
$x:ty       // type: u32, Vec<String>
$x:pat      // pattern: Some(_), 1..=5
$x:block    // block: { .. }
$x:item     // item: fn, struct, impl
$x:literal  // literal: 42, "metin"
$x:tt       // a single token tree (anything)

ident and ty let macros generate function and type definitions; this is impossible with functions.

An item-generating macro

To reduce repetitive definitions to a single line:

macro_rules! sabit_fn {
    ($ad:ident, $tur:ty, $deger:expr) => {
        fn $ad() -> $tur {
            $deger
        }
    };
}

sabit_fn!(surum, &'static str, "1.0");
sabit_fn!(port, u16, 8080);
println!("{} {}", surum(), port());

The standard library generates dozens of trait implementations for number types with macros like this.

Practice Function-generating macro

Write the sabit_fn! macro above and generate the functions surum (&'static str, "1.0") and port (u16, 8080). Print the results of both functions separated by a space.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
macro_rules! sabit_fn {
    ($ad:ident, $tur:ty, $deger:expr) => {
        fn $ad() -> $tur {
            $deger
        }
    };
}

sabit_fn!(surum, &'static str, "1.0");
sabit_fn!(port, u16, 8080);

fn main() {
    println!("{} {}", surum(), port());
}

Expected output

1.0 8080

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which fragment is needed for a macro to generate a new function name?

  • literal
  • ident Correct answer
  • expr
  • ty

Explanation: A name taken with $ad:ident is used in the body as fn $ad().

2 Type fragment

Question
macro_rules! sabit_fn {
    ($ad:ident, $tur:____, $deger:expr) => {
        fn $ad() -> $tur { $deger }
    };
}
Answer
macro_rules! sabit_fn {
    ($ad:ident, $tur:ty, $deger:expr) => {
        fn $ad() -> $tur { $deger }
    };
}

Explanation: The ty fragment matches a type.

3 Fragment and example

Term Meaning
ident surum
ty &'static str
expr "1.0"
pat Some(_)

All lessons in Advanced