gpt4 book ai didi

rust - .expect( format!() ) : expected `&str` , 找到结构 `String`

转载 作者:行者123 更新时间:2023-12-05 08:46:34 63 4
gpt4 key购买 nike

我试图创建一个宏来替换,

first: Some(first.as_ref().parse::<u64>().expect("Could not parse 'first'"))

我在其他模块(如 Clap with values_t!)中看到过这样做,我对此进行抽象的尝试并未扩展到类型。这是我写的,

macro_rules! parse_u64 {
($var:ident) => {
Some(
$var
.as_ref()
.parse::<u64>()
.expect( format!("Could not parse '{:?}'", stringify!($var)) )
)
};
}

这会产生以下错误,

first: parse_u64!(first),
^^^^^^^^^^^^^^^^^ expected `&str`, found struct `String`

我在这里做错了什么:这是一个简单的宏,链中只有三件事?为什么会出现此错误,我该如何解决?


你可以在这个 Rust Playground example 中看到这个

最佳答案

正如您在自己的回答中提到的,expect 采用 &str,因此您不能直接传入 String:

.expect(format!("Could not parse '{:?}'", stringify!($var)).as_str())

但是,即使没有错误,这也会执行字符串格式化(并分配一个新字符串),所以我建议:

.unwrap_or_else(|err| panic!("Could not parse '{:?}': {}", stringify!($var), err))

这实际上与上面相同,期望unwrap_or_else仅在错误情况下调用其闭包。


或者,在这种特定情况下,您可以在编译时将字符串文字与 concat! 连接起来。 ,这也避免了 format! 的开销:

.expect(concat!("Could not parse '", stringify!($var), "'"))

关于rust - .expect( format!() ) : expected `&str` , 找到结构 `String`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69520309/

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