以下Rust代码编译并运行没有任何问题.
fn main() {
let text = "abc";
println!("{}", text.split(' ').take(2).count());
}
Run Code Online (Sandbox Code Playgroud)
在那之后,我尝试了类似的东西....但它没有编译
fn main() {
let text = "word1 word2 word3";
println!("{}", to_words(text).take(2).count());
}
fn to_words(text: &str) -> &Iterator<Item = &str> {
&(text.split(' '))
}
Run Code Online (Sandbox Code Playgroud)
主要问题是我不确定函数to_words()应该具有什么返回类型.编译器说:
error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
--> src/main.rs:3:43
|
3 | println!("{}", to_words(text).take(2).count());
| ^^^^^
|
= note: the method `count` exists but the following trait bounds were not satisfied:
`std::iter::Iterator<Item=&str> : std::marker::Sized`
`std::iter::Take<std::iter::Iterator<Item=&str>> …Run Code Online (Sandbox Code Playgroud) 我定义了一个结构,它有一个定义静态生命周期的函数:
impl MyStruct {
pub fn doSomething(&'static self) {
// Some code goes here
}
}
Run Code Online (Sandbox Code Playgroud)
我像这样从 main 消费它:
fn main() {
let obj = MyStruct {};
obj.doSomething();
}
Run Code Online (Sandbox Code Playgroud)
它用于doSomething在应用程序的生命周期内阻塞和执行的调用。
我遇到了生命周期检查的问题,它指出它可能比main函数的寿命更长,这对我来说似乎很奇怪,因为一旦main完成应用程序应该退出。
有没有办法实现这一目标?
我在迭代器上应用了一个闭包,我想使用stable,所以我想返回一个盒装Iterator.这样做的显而易见的方法如下:
struct Foo;
fn into_iterator(myvec: &Vec<Foo>) -> Box<dyn Iterator<Item = &Foo>> {
Box::new(myvec.iter())
}
Run Code Online (Sandbox Code Playgroud)
这是失败的,因为借用检查器无法推断出适当的生命周期.
经过一番研究,我找到了正确的方法来返回迭代器?,这让我想补充一下+ 'a:
fn into_iterator<'a>(myvec: &'a Vec<Foo>) -> Box<dyn Iterator<Item = &'a Foo> + 'a> {
Box::new(myvec.iter())
}
Run Code Online (Sandbox Code Playgroud)
但我不明白
我有一个包含值的结构,我想获得一个对该值进行操作的函数:
struct Returner {
val: i32,
}
impl<'a> Returner {
fn get(&'a self) -> Box<Fn(i32) -> i32> {
Box::new(|x| x + self.val)
}
}
Run Code Online (Sandbox Code Playgroud)
编译失败:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:7:18
|
7 | Box::new(|x| x + self.val)
| ^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime 'a as defined on the impl at 5:1...
--> src/main.rs:5:1
|
5 | impl<'a> Returner {
| ^^^^^^^^^^^^^^^^^
= note: ...so that the types are …Run Code Online (Sandbox Code Playgroud)