我想在Rust中为一个闭包声明一个生命周期,但我找不到添加生命周期声明的方法.
use std::str::SplitWhitespace;
pub struct ParserError {
pub message: String,
}
fn missing_token(line_no: usize) -> ParserError {
ParserError {
message: format!("Missing token on line {}", line_no),
}
}
fn process_string(line: &str, line_number: usize) -> Result<(), ParserError> {
let mut tokens = line.split_whitespace();
match try!(tokens.next().ok_or(missing_token(line_number))) {
"hi" => println!("hi"),
_ => println!("Something else"),
}
// The following code gives "cannot infer appropriate lifetime.....
// let nt = |t: &mut SplitWhitespace| t.next().ok_or(missing_token(line_number));
// match try!(nt(&mut tokens)) {
// "there" => println!("there"),
// …Run Code Online (Sandbox Code Playgroud) 我对下面的生命周期发生了什么感到困惑:
struct Foo{}
impl Foo {
fn foo(&self, _s: &str) {}
}
fn main() {
let foo = &Foo{};
let closure = |s| foo.foo(s);
// Part 1: error message about wrong lifetime in FnOnce
take_closure(closure);
// Part 2: no error when inlined
take_closure(|s| foo.foo(s));
// Part 3: no error when `dyn`d and given explicit signature
let closure: &dyn Fn(&str) -> _ = &|s| foo.foo(s);
take_closure(closure);
}
fn take_closure(f: impl Fn(&str) -> ()) {
let s = get_string();
f(&s)
}
fn …Run Code Online (Sandbox Code Playgroud) 虽然下面的代码是一个早期的原型,并且不要过于认真地考虑我在这个阶段如何实现协议缓冲区,但我无法理解生锈编译器带来的错误信息.
src\main.rs:89:9:89:36错误:类型不匹配解析
for<'r> <[closure src\ma in.rs:75:33: 88:10] as core::ops::FnOnce<(u32, gpb::definitions::WireType, &'r collections::vec::Vec<u8>, usize)>>::Output == usize:期望绑定生存期参数,找到具体生存期[E0271] src\main.rs:89 gpb :: decoding :: read_message(source,field_handler);
即使在阅读了有关lifetimes等的3篇文章章节之后.人.我没有遇到"具体的生命周期"这个术语,因此无法弄清楚这个错误与哪些代码有关.闭包本身,一个或多个参数,返回码?关闭的通过 read_message()?...
main.rs片段
fn from_gpb( source : &Vec<u8>) -> TimeMessage {
fn init_vec_u64( count : usize, init_value : u64) -> Vec<u64> {
let mut result = Vec::<u64>::with_capacity(count);
for i in 0..count {
result.push(init_value);
}
result
}
let mut message_id : u32 = 0;
let mut times_sec = init_vec_u64(4,0u64);
let mut times_usec = init_vec_u64(4,0u64);
let mut max_time_index = …Run Code Online (Sandbox Code Playgroud)