Como faço para formatar! retornar um & str a partir de uma expressão condicional?
Eu me deparei com este problema em queformat!
cria um valor temporário em um padrão que não está ancorado em nada, tanto quanto eu o entendo.
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);
Neste código, o tipo decategory
é um&str
, que é satisfeito retornando um literal como"Between 0 and 9"
. Se eu quiser formatar o valor correspondente a uma fatia usandoas_str()
, recebo um erro:
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)
Li algumas vezes e encontrei pessoas com problemas semelhantes, mas não consegui encontrar nenhuma soluçã
Uma solução simples seria tercategory
seja umString
em vez de um&str
, mas não gosto da ideia de colocar.to_string()
no final de cada literal no padrão, pois não é tão limp
Existe uma maneira de resolver o problema ou preciso apenas contorná-l