调用一个返回字符串文字错误数组的函数,其中包含“无法返回引用局部变量的值”

时间:2019-11-20 03:23:47

标签: rust

parse_winning_hand函数的目标是接受5个i32的向量,然后将相应的字母附加到return_val的第i个索引(从0到5) 。 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

我一直在寻找解决此问题的解决方案,但是该解决方案不适用于我的需求,或者由于我缺乏知识而无法理解发布的解决方案。为什么我得到错误?我该如何解决?

1 个答案:

答案 0 :(得分:0)

您的示例可以为此reduced

$outputData[1];

//On expanding

array:6 [▼
  "id" => 3
  "post_id" => 115
  "status" => "active"
  "updated_at" => "2019-11-15 12:57:41"
  "created_at" => "2019-11-15 12:57:41"
]
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] // ^~~~~~~ 的情况下,lifetime elision使函数签名将返回值的生存期与输入值的生存期联系起来:

'static

这意味着返回的值不可能超过传入的fn parse_winning_hand<'a>(_: &'a [i32]) -> [&'a str; 1]

另请参阅: