Rustlang:在宏中添加 return 语句

geo*_*tle 4 macros return rust rust-macros

我正在学习 rustlings 课程,以便学习 rustlang,并且正在做测验 4。以下是我找到的解决方案。

macro_rules! my_macro {
    ($val:expr) => {
       format!("Hello {}", $val)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_my_macro_world() {
        assert_eq!(my_macro!("world!"), "Hello world!");
    }

    #[test]
    fn test_my_macro_goodbye() {
        assert_eq!(my_macro!("goodbye!"), "Hello goodbye!");
    }
}
Run Code Online (Sandbox Code Playgroud)

但在此之前,我尝试了以下方法但没有成功:

macro_rules! my_macro {
    ($val:expr) => {
       return format!("Hello {}", $val)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_my_macro_world() {
        assert_eq!(my_macro!("world!"), "Hello world!");
    }

    #[test]
    fn test_my_macro_goodbye() {
        assert_eq!(my_macro!("goodbye!"), "Hello goodbye!");
    }
}
Run Code Online (Sandbox Code Playgroud)

这个无效解决方案的唯一区别是关键字return。在这种情况下,编译器会输出完整的错误和警告列表。

为什么这是不正确的?Rust 宏中不允许使用 return 语句吗?

Lam*_*iry 5

当您调用宏时,其主体将粘贴*到调用它的位置。

这意味着在第二个片段中:

#[test]
fn test_my_macro_world() {
    assert_eq!(my_macro!("world!"), "Hello world!");
}
Run Code Online (Sandbox Code Playgroud)

扩展为:

#[test]
fn test_my_macro_world() {
    assert_eq!(return format!("Hello {}", "world!"), "Hello world!");
}
Run Code Online (Sandbox Code Playgroud)

这会导致类型错误。


* 比这更复杂一点:还有一些魔法可以防止命名冲突。