如何使用结构和隐式生命周期来推断实现的适当生命周期?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用结构和隐式生命周期来推断实现的适当生命周期?相关的知识,希望对你有一定的参考价值。
如何解决此错误?当我在impl
中使用“匿名生存期”时,我到底要告诉编译器什么?
struct LineHandlerInfo<'a> label: &'a str, match_literal: &'a str, f: fn(&str) -> Option<&str>, struct Game<'a> handlers: Vec<LineHandlerInfo<'a>>, impl Game<'_> fn match_str<'a>( &'a mut self, label: &'a str, match_literal: &'a str, mut f: fn(&str) -> Option<&str>, ) let mut lh = LineHandlerInfo label, match_literal, f, ; self.handlers.push(lh); fn main() let mut g = Game handlers: Vec::new(), ; g.match_str("echo hello", "hello", |s| println!("", s); None );
当我尝试编译时,出现以下错误:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements --> src/main.rs:18:22 | 18 | let mut lh = LineHandlerInfo | ^^^^^^^^^^^^^^^ | note: first, the lifetime cannot outlive the lifetime 'a as defined on the method body at 12:18... --> src/main.rs:12:18 | 12 | fn match_str<'a>( | ^^ note: ...so that reference does not outlive borrowed content --> src/main.rs:19:13 | 19 | label, | ^^^^^ note: but, the lifetime must be valid for the lifetime '_ as defined on the impl at 11:11... --> src/main.rs:11:11 | 11 | impl Game<'_> | ^^ = note: ...so that the expression is assignable: expected LineHandlerInfo<'_> found LineHandlerInfo<'_>
如何解决此错误,当我已经在结构上具有生存期时,当我在
impl Game
上指定生存期时,该告诉编译器什么?
如何解决此错误?当我在impl中使用“匿名生存期”时,我到底要告诉编译器什么? struct LineHandlerInfo 标签:&'a str,match_literal:&'a ...
答案
我该如何解决此错误?
以上是关于如何使用结构和隐式生命周期来推断实现的适当生命周期?的主要内容,如果未能解决你的问题,请参考以下文章
我如何让impl Trait使用适当的生命周期来对其中有另一个生命周期的值进行可变引用?