所以在这里,我和Rustlings一起运,直到我被测试4豁免。
它希望我编写一个满足以下代码的宏:
fn main() {
if my_macro!("world!") != "Hello world!" {
panic!("Oh no! Wrong output!");
}
}
所以,我写了这个:
macro_rules! my_macro {
($val:expr) => {
println!("Hello {}", $val);
}
}
而Rustling吐了出来:
error[E0308]: mismatched types
--> exercises/test4.rs:15:31
|
15 | if my_macro!("world!") != "Hello world!" {
| ^^^^^^^^^^^^^^ expected (), found reference
|
= note: expected type `()`
found type `&'static str`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
哪个,你知道。我明白了我明白问题是什么,但我不明白如何编写一个满足代码的宏。我可以更改我正在测试的代码,但这不是测试要我做的。我只想写一个宏。我很难过。我也不明白在模块中封装宏是如何帮助的,但测试表明它是对模块和宏的测试。
println!
将打印到stdout
。相反,您只想格式化字符串并从宏返回它。改为使用format!
,然后删除;
,使其返回表达式而不是()
:
macro_rules! my_macro {
($val:expr) => {
format!("Hello {}", $val)
}
}