【问题标题】:Return a str - Rust Lifetimes [duplicate]返回一个 str - Rust Lifetimes [重复]
【发布时间】:2017-07-13 01:30:29
【问题描述】:

我在尝试返回字符串时遇到了一些麻烦。我一直在尝试各种方法来定义我的变量和返回值,以便我可以返回字符串原语,但我得到了一系列与生命周期相关的错误消息。

pub fn raindrops(int: u64) -> &'a str {
    let mut out = String::new();

    if int % 3 == 0 {
        out.push_str("Pling");
    }
    if int % 5 == 0 {
        out.push_str("Plang");
    }
    if int % 7 == 0 {
        out.push_str("Plong");
    }
    if out.is_empty() {
        out.push_str(&format!("{}", int));
    }

    out.shrink_to_fit();

    return out.as_str();
}

错误:

error[E0261]: use of undeclared lifetime name `'a`
 --> src/lib.rs:1:32
  |
1 | pub fn raindrops(int: u64) -> &'a str {
  |                                ^^ undeclared lifetime

error: aborting due to previous error

error: Could not compile `raindrops`.
Build failed, waiting for other jobs to finish...
error[E0261]: use of undeclared lifetime name `'a`
 --> src/lib.rs:1:32
  |
1 | pub fn raindrops(int: u64) -> &'a str {
  |                                ^^ undeclared lifetime

【问题讨论】:

标签: rust


【解决方案1】:

在这种情况下您不能返回&str,因为它会指向out 的内容,该内容在函数末尾超出范围。您必须改为返回字符串 out

或者,如果你想限制分配,你可以返回一个枚举,它可以是以下之一:

Pling,
Plang,
Plong,
Other(u64)

然后根据值打印响应。

【讨论】:

  • 成功了!谢谢,我想我太复杂了。
  • 作为一种优化,可以返回 Cow 而不是 String。这将确保在返回静态字符串时不会发生动态分配。
猜你喜欢
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2021-04-30
  • 2020-07-07
相关资源
最近更新 更多