rust - 调用返回字符串字面量数组的函数,出现“无法返回引用局部变量的值”错误
问题描述
该parse_winning_hand
函数的目标是接受一个 5 i32
s 的向量,然后将相应的字母附加到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
我已经搜索了此问题的解决方案,但该解决方案不适用于我的需求,或者由于我缺乏知识而无法理解发布的解决方案。为什么我收到错误消息?我如何解决它?
解决方案
您的示例可以简化为:
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
传入的值长。
也可以看看:
推荐阅读
- sql-server - 将 SQL Server 中的日期时间转换为 Redshift 的正确格式
- matlab - 变换对象,使其法线向量对齐 z 轴
- kubernetes - 无法拉取镜像以在 kubernetes 中运行 pod
- python-2.7 - python2.7和tox和virtualenv在pycharm调试时的集成(社区)
- python - 使用字符串“BANANA”中的计数使用python的str.count()inbuild函数查找“ANA”作为子字符串时出错
- java - 如何将一个数组列表深度复制到另一个数组列表中
- ios - 如何以编程方式在 UILabel 上调整 sizeToFit 宽度和高度?
- javascript - 匿名函数的等待/异步
- python - (Python3)将对象传递给导入的模块函数
- powershell - 在我的 AD powershell 脚本中添加 Get-ADuser 属性时遇到问题