我如何制作格式!从条件表达式返回 &str? [英] How do I make format! return a &str from a conditional expression?
问题描述
我遇到了这个问题,其中 format!
在一个模式中创建了一个临时值,据我所知,该值没有锚定到任何东西.
I happened upon this problem where format!
creates a temporary value in a pattern that is not anchored to anything, as far as I understand it.
let x = 42;
let category = match x {
0...9 => "Between 0 and 9",
number @ 10 => format!("It's a {}!", number).as_str(),
_ if x < 0 => "Negative",
_ => "Something else",
};
println!("{}", category);
在这段代码中,category
的类型是一个&str
,它通过返回一个像Between 0 and 9"这样的文字来满足.代码>.如果我想使用
as_str()
将匹配的值格式化为切片,则会出现错误:
In this code, the type of category
is a &str
, which is satisfied by returning a literal like "Between 0 and 9"
. If I want to format the matched value to a slice using as_str()
, then I get an error:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:5:24
|
3 | let category = match x {
| -------- borrow later stored here
4 | 0...9 => "Between 0 and 9",
5 | number @ 10 => format!("It's a {}!", number).as_str(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
|
= note: consider using a `let` binding to create a longer lived value
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
我读了一些书,发现有类似问题的人,但我似乎找不到任何解决方案.
I have done some reading, and found people with similar problems, but I couldn't seem to find any solution.
一个简单的解决方法是让 category
成为 String
而不是 &str
,但我不喜欢这个想法必须将 .to_string()
放在模式中每个文字的末尾,因为它不是那么干净.
A simple workaround would be to have category
be a String
instead of a &str
, but I don't like the idea of having to put .to_string()
on the end of every literal in the pattern, as it's not as clean.
有没有办法解决这个问题,或者我只需要解决它?
Is there a way to solve the problem, or do I just need to work around it?
推荐答案
这是 90% 的 以切片形式返回本地字符串(&str),请参阅其他多种解决方案.
This is 90% a duplicate of Return local String as a slice (&str), see that for multiple other solutions.
还有一种额外的可能性,因为这一切都在一个函数中:您可以为 String
声明一个变量,并且仅在需要分配时才设置它.编译器(斜向)建议:
There's one extra possibility since this is all in one function: You can declare a variable for the String
and only set it when you need to allocate. The compiler (obliquely) suggests this:
考虑使用 let
绑定来创建更长寿的值
consider using a
let
binding to create a longer lived value
fn main() {
let x = 42;
let tmp;
let category = match x {
0...9 => "Between 0 and 9",
number @ 10 => {
tmp = format!("It's a {}!", number);
&tmp
}
_ if x < 0 => "Negative",
_ => "Something else",
};
println!("{}", category);
}
这与使用 Cow
大致相同,只是由编译器处理而不是特定类型.
This is mostly the same as using a Cow
, just handled by the compiler instead of a specific type.
另见:
这篇关于我如何制作格式!从条件表达式返回 &str?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!