[&str; 5] { let mut temp_hand-6ren">
gpt4 book ai didi

rust - 调用返回字符串文字数组的函数,错误为 "cannot return value referencing local variable"

转载 作者:行者123 更新时间:2023-11-29 08:30:37 31 4
gpt4 key购买 nike

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

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

最佳答案

你的例子可以是reduced对此:

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)

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

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

没有'staticlifetime elision导致函数签名将返回值的生命周期与输入值的生命周期联系起来:

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

这意味着返回值不可能超过传入的 Vec

另见:

关于rust - 调用返回字符串文字数组的函数,错误为 "cannot return value referencing local variable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58946151/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com