如何为Option< closure>指定有效期? [英] How to specify a lifetime for an Option<closure>?
问题描述
我试图将一个字段放在应该包含Option<closure>
的结构上.
I'm trying to put a field on a struct that should hold an Option<closure>
.
但是,Rust对我大吼大叫,我必须指定生命周期(不是我真的会抱怨).我正在尽力做到这一点,但是Rust对我的想法永远不满意.看看我的内联注释,了解我得到的编译错误.
However, Rust is yelling at me that I have to specify the lifetime (not that I would have really grokked that yet). I'm trying my best to do so but Rust is never happy with what I come up with. Take a look at my inline comments for the compile errors I got.
struct Floor{
handler: Option<|| ->&str> //this gives: missing lifetime specifier
//handler: Option<||: 'a> // this gives: use of undeclared lifetime name `'a`
}
impl Floor {
// I guess I need to specify life time here as well
// but I can't figure out for the life of me what's the correct syntax
fn get(&mut self, handler: || -> &str){
self.handler = Some(handler);
}
}
推荐答案
这有点棘手.
作为一般经验法则,每当在数据结构中存储借来的引用(即&
类型)时,都需要命名其生存期.在这种情况下,使用'a
使您处在正确的轨道上,但是必须在当前作用域中引入'a
.与引入类型变量的方式相同.因此,定义您的Floor
结构:
As a general rule of thumb, whenever you're storing a borrowed reference (i.e., an &
type) in a data structure, then you need to name its lifetime. In this case, you were on the right track by using a 'a
, but that 'a
has to be introduced in the current scope. It's done the same way you introduce type variables. So to define your Floor
struct:
struct Floor<'a> {
handler: Option<|| -> &'a str>
}
但是这里还有另一个问题.闭包本身也是带有生存期的引用,也必须命名.因此,这里有两个不同的生命!试试这个:
But there's another problem here. The closure itself is also a reference with a lifetime, which also must be named. So there are two different lifetimes at play here! Try this:
struct Floor<'cl, 'a> {
handler: Option<||:'cl -> &'a str>
}
对于您的impl Floor
,您 还需要将这些生存期引入范围:
For your impl Floor
, you also need to introduce these lifetimes into scope:
impl<'cl, 'a> Floor<'cl, 'a> {
fn get(&mut self, handler: ||:'cl -> &'a str){
self.handler = Some(handler);
}
}
从技术上讲,您可以将其缩减为一个生存期,并使用||:'a -> &'a str
,但这意味着返回的&str
始终具有与闭包本身相同的生存期,我认为这是一个错误的假设.
You could technically reduce this down to one lifetime and use ||:'a -> &'a str
, but this implies that the &str
returned always has the same lifetime as the closure itself, which I think is a bad assumption to make.
这篇关于如何为Option< closure>指定有效期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!