如何制作格式!从条件表达式返回& str? [英] How do I make format! return a &str from a conditional expression?

查看:150
本文介绍了如何制作格式!从条件表达式返回& str?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到了这个问题,据我所知,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.

这篇关于如何制作格式!从条件表达式返回&amp; str?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆