gpt4 book ai didi

rust - 如何避免使用可选message参数的函数的重复代码?

转载 作者:行者123 更新时间:2023-12-03 11:40:33 28 4
gpt4 key购买 nike

我想编写自己的assert函数,该函数可以有选择地显示一条消息:

fn foo(msg: Option<&str>) {
if let Some(m) = msg {
panic!("{} - Something went wrong: {}", m, "additional info");
} else {
panic!("Something went wrong: {}", "additional info")
}
}

如何避免这样的重复代码?如何避免对消息字符串进行多次分配(重新分配)?

最佳答案

不打印时,请使用空字符串。

fn foo(msg: Option<&str>) {
panic!("{}{}Something went wrong: {}",
{ if let Some(m) = msg { m } else { "" } },
{ if let Some(_m) = msg { " - " } else { "" } },
"additional info");
}

在rustfmt之后看起来像这样:
fn foo(msg: Option<&str>) {
panic!(
"{}{}Something went wrong: {}",
{
if let Some(m) = msg {
m
} else {
""
}
},
{
if let Some(_m) = msg {
" - "
} else {
""
}
},
"additional info"
);
}

关于rust - 如何避免使用可选message参数的函数的重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60747205/

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