gpt4 book ai didi

types - 鲁斯类(class)Test4.rs宏返回类型问题

转载 作者:行者123 更新时间:2023-12-03 11:43:41 24 4
gpt4 key购买 nike

我正在做RuSTLings Rust-lang course并正在exercises/test4.rs上工作

这是类(class)中唯一没有提示的练习。因此,经过一段时间的研究,我正在努力在这里获得提示!

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

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

当我尝试编译时,出现以下错误:
error[E0308]: mismatched types
--> test4.rs:20:31
|
20 | if my_macro!("world!") != "Hello world!" {
| ^^^^^^^^^^^^^^ expected (), found reference
|
= note: expected type `()`
found type `&'static str`

error: aborting due to previous error

问题似乎是基于这样的事实,Rust宏的默认返回类型是一个空的元组类型(即 expected type ()),我们将其与静态字符串进行比较。

如果该练习的参数允许我更改main函数中的代码,那么该练习似乎会更简单一些。但是,根据指令,唯一要做的就是编写一个导致代码进行编译的宏。

据我了解,您不能显式声明宏的返回类型。因此,我对如何进行一无所知。

最佳答案

我认为实现可能会简单得多:

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

关于types - 鲁斯类(class)Test4.rs宏返回类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59440514/

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