我正在做Rust-lang course,也在做exercises/test4.rs
这是课程中唯一没有提示的练习。因此,在研究了一段时间之后,我想在这里得到这个提示!
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函数中的代码,那么练习看起来会更简单一些。但是,根据指令,唯一要做的事情就是编写一个宏来编译代码。
据我所知,您不能显式声明宏的返回类型。因此,我不知所措,不知如何继续下去。
发布于 2019-12-22 09:25:46
所以这是我想出的可行的答案:
fn function_rules(expr:&str)-> String{
let a = "Hello";
let b = expr;
let result = [a, b].join(" ");
return result.to_string();
}
macro_rules! my_macro {
() => {
println!("Hello!");
};
($val:expr) => {
//println!("Hello {}", $val);
function_rules($val)
}
}
fn main() {
if my_macro!("world!") != "Hello world!" {
panic!("Oh no! Wrong output!");
}
}我解决这个问题的很大一部分是处理String vs &str类型,其中很好的一部分可以在here中找到。
根据指令参数,代码编译时不会以任何方式修改main()函数。我认为一个更优雅的解决方案是编写一个返回正确类型的宏,而不依赖于额外的函数。假设这是可能的!
发布于 2020-01-12 00:43:14
我认为实现可以简单得多:
macro_rules! my_macro {
($val:expr) => {
format!("Hello {}", $val)
}
}https://stackoverflow.com/questions/59440514
复制相似问题