- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个错误,其他时候我有类似的事情,我已经能够以不同的方式解决,但现在不是在这种情况下如何解决:
borrowed value does not live long enough in
我将失败的代码移动了一个更简单的,但我找不到错误:
fn main(){
let mut v: Vec<&Fn(i32) -> i32> = Vec::new();
v.push(&ops_code1);
//v.push(&ops_code2);
//v.push(&ops_code3);
}
fn ops_code1(value: i32) -> i32 {
..//
error: borrowed value does not live long enough
v.push(&ops_code1);
最佳答案
您在这里所做的是创建闭包 Vec。在 Rust 中,静态函数的处理方式与闭包略有不同,因此当我们创建引用时,实际上会创建一个闭包。如果我们在创建 Vec 之后这样做,结果闭包的生命周期会比 Vec 短,这是一个错误。我们可以使用 let 在 Vec 之前创建闭包,提供足够长的生命周期,比 Vec 长:
fn main() {
let extended = &ops_code1;
let mut v: Vec<&Fn(i32) -> i32> = Vec::new();
// Note that placing it here does not work:
// let extended = &ops_code1;
v.push(extended);
//v.push(&ops_code2);
//v.push(&ops_code3);
}
fn ops_code1(value: i32) -> i32 {
println!("ops_code1 {}", value);
value
}
但是,如果您只使用静态函数——而不是闭包——下面的代码也可以正常工作,并且让您避免额外的 let:
fn main() {
let mut v: Vec<fn(i32) -> i32> = Vec::new();
v.push(ops_code1);
v.push(ops_code2);
}
fn ops_code1(value: i32) -> i32 {
println!("ops_code1 {}", value);
value
}
fn ops_code2(value: i32) -> i32 {
println!("ops_code2 {}", value);
value
}
第三种选择是使用盒装闭包,它让您可以同时使用闭包和静态函数而无需额外的 let,但有其自身的权衡:
fn main() {
let mut v: Vec<Box<Fn(i32) -> i32>> = Vec::new();
v.push(Box::new(ops_code1));
v.push(Box::new(ops_code2));
for f in v {
f(1);
}
}
fn ops_code1(value: i32) -> i32 {
println!("ops_code1 {}", value);
value
}
fn ops_code2(value: i32) -> i32 {
println!("ops_code2 {}", value);
value
}
关于rust - 在这种情况下,借用的值(value)不够长( Vec<&Fn(i32) -> i32> ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36392323/
killer = killer.Replace("(", "\("); 试图在大括号前放置'\',它显示“错误1无法识别的转义序列” 我还尝试在其前面加上“@”,但这会导致两个反斜杠。 最佳答案 使用
我创建了一个包含书籍的小型数据库,并试图在 C# 中使用正则表达式获取书名、作者和书籍年份,但出现错误。 数据库看起来像这样: Eragon // Christopher Paolini // 200
当我尝试编译时 scalala我得到一个 OutOfMemoryError: > compile [info] [info] == compile == [info] Source analysi
这个问题在这里已经有了答案: Regex escape with \ or \\? (5 个答案) 关闭 4 年前。 我遇到了 ) 不够的错误,但据我所知,我已经得到了所有的 )。 行获取错误: s
我正在尝试使用 pthread_create 函数创建一个线程。电话是这样的:res pthread_create(&threadID, &atributte, function, argument)
我需要能够遍历我的整个对象图并记录所有成员字段的所有内容。 例如:对象 A 具有对象 B 的集合,对象 B 具有对象 C 的集合,并且 A、B、C 上有附加字段,等等。 Apache Commons
我的 create.jspx 中有一行,如下所示: 此字段显示一个框,其中的行由 2 个实体之间的关系 @ManyToMany 填充。 现在的问题是,第一个实体只有一个填充此框的 String 属性
ctags -R dirName, vim -t Tags 非常强大,因为在这两个命令之后,你现在可以在该项目的代码之间导航,例如你可以使用 :tag functionName 跳转到某个函数的代码,
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: iphone 5 simulator - Cannot click on bottom of screen?
我有一个庞大的关键字表,一个关键字出现在一个外键中,例如 key=2 word=download key=3 word=download key=4 word=game 目前我有另一个字段称为字母索引
这个问题在这里已经有了答案: How to change stack size for a .NET program? (4 个答案) 关闭 7 年前。 我在 bmp 中有以下用于“blob 填充”
我是一名优秀的程序员,十分优秀!