首页 > 解决方案 > 调用返回字符串字面量数组的函数,出现“无法返回引用局部变量的值”错误

问题描述

parse_winning_hand函数的目标是接受一个 5 i32s 的向量,然后将相应的字母附加到return_val(从 0 到 5)的第 i 个索引。是一个在运行结束时deal调用的驱动程序函数:parse_winning_hand

fn parse_winning_hand(hand: &Vec<i32>) -> [&str; 5] {
    let mut temp_hand = hand.to_vec();
    let mut return_val = ["12", "12", "12", "12", "12"];
    for i in 0..5 {
        let popped = temp_hand.pop().unwrap();
        let mut suit = "X";
        if popped < 14 {
            suit = "C";
        } else if popped < 27 {
            suit = "D";
        } else if popped < 40 {
            suit = "H";
        } else {
            suit = "S";
        }
        return_val[i] = suit;
    }
    return return_val;
}

fn deal(arr: &[i32]) -> [&'static str; 5] {
    // ...
    let decided_winner = decide_winner(hand_one_score, hand_two_score);
    if decided_winner == 1 {
        let ret = parse_winning_hand(&hand_one);
        return ret;
    } else {
        let ret = parse_winning_hand(&hand_two);
        return ret;
    }
}

我在编译过程中遇到的错误是:

error[E0515]: cannot return value referencing local variable `hand_one`
   --> Poker.rs:276:10
    |
275 |         let ret = parse_winning_hand(&hand_one);
    |                                      --------- `hand_one` is borrowed here
276 |         return ret;
    |                ^^^ returns a value referencing data owned by the current function

error[E0515]: cannot return value referencing local variable `hand_two`
   --> Poker.rs:279:10
    |
278 |         let ret = parse_winning_hand(&hand_two);
    |                                      --------- `hand_two` is borrowed here
279 |         return ret;
    |                ^^^ returns a value referencing data owned by the current function

我已经搜索了此问题的解决方案,但该解决方案不适用于我的需求,或者由于我缺乏知识而无法理解发布的解决方案。为什么我收到错误消息?我如何解决它?

标签: rust

解决方案


您的示例可以简化为:

fn parse_winning_hand(_: &[i32]) -> [&str; 1] {
    ["0"]
}

fn deal() -> [&'static str; 1] {
    parse_winning_hand(&vec![])
}
error[E0515]: cannot return value referencing temporary value
 --> src/lib.rs:6:5
  |
6 |     parse_winning_hand(&vec![])
  |     ^^^^^^^^^^^^^^^^^^^^------^
  |     |                   |
  |     |                   temporary value created here
  |     returns a value referencing data owned by the current function
  |
  = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

这是因为您忘记指定'static返回类型的生命周期parse_winning_hand

fn parse_winning_hand(_: &[i32]) -> [&'static str; 1]
//                                    ^~~~~~~

如果没有'static,生命周期省略会导致函数签名将返回值的生命周期与输入值的生命周期联系起来:

fn parse_winning_hand<'a>(_: &'a [i32]) -> [&'a str; 1]

这意味着返回的值不可能比Vec传入的值长。

也可以看看:


推荐阅读