Skip to content

Fix log_call! macro example in "Rust for Python Programmers" (ch12 closures and iterators)#84

Open
Chandan-Kalita wants to merge 1 commit intomicrosoft:mainfrom
Chandan-Kalita:patch-1
Open

Fix log_call! macro example in "Rust for Python Programmers" (ch12 closures and iterators)#84
Chandan-Kalita wants to merge 1 commit intomicrosoft:mainfrom
Chandan-Kalita:patch-1

Conversation

@Chandan-Kalita
Copy link
Copy Markdown

@Chandan-Kalita Chandan-Kalita commented Apr 8, 2026

Fixes an issue in the log_call! macro where it expands to multiple statements instead of a single expression, causing a type mismatch in usage.

Problem

The macro was defined as:

macro_rules! log_call {
    ($func_name:expr, $body:expr) => {
        println!("Calling {}", $func_name);
        $body
    };
}

When used in expression position:

fn process(data: &str) -> String {
    log_call!("process", data.to_uppercase())
}

it expands to:

println!(...);
data.to_uppercase()

This results in a compilation error:

expected String, found ()
because the macro does not expand to a single expression.

Fix

Wrap the macro body in a block expression:

macro_rules! log_call {
    ($func_name:expr, $body:expr) => {{
        println!("Calling {}", $func_name);
        $body
    }};
}

This ensures the macro expands to a single expression whose value is the result of $body.

Result

  • Fixes compilation error in the example
  • Demonstrates correct macro usage in expression position
  • Improves clarity for learners

@Chandan-Kalita Chandan-Kalita changed the title Fix log_call macro to properly log function calls in python-book/src/ch12-closures-and-iterators.md Fix log_call! macro example in "Rust for Python Programmers" (ch12 closures and iterators) Apr 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant