gpt4 book ai didi

string - 如何从声明性宏返回一个新字符串?

转载 作者:行者123 更新时间:2023-11-29 08:05:52 26 4
gpt4 key购买 nike

所以我在这里,和 RuSTLings 一起开卡车,直到我对测试 4 大开眼界。

它要我写一个满足下面代码的宏:

fn main() {
if my_macro!("world!") != "Hello world!" {
panic!("Oh no! Wrong output!");
}
}

所以,我这样写:

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

RuSTLings 吐出了这个:

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)
}
}

关于string - 如何从声明性宏返回一个新字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54930966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com