相关疑难解决方法(0)

返回迭代器(或任何其他特征)的正确方法是什么?

以下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)

rust

92
推荐指数
1
解决办法
2万
查看次数

如何在Rust中进行错误处理以及常见的陷阱是什么?

我注意到Rust没有例外.如何在Rust中进行错误处理以及常见的陷阱是什么?有没有办法通过加注,捕获,重新加注和其他东西来控制流量?我发现这方面的信息不一致.

error-handling rust

14
推荐指数
1
解决办法
5226
查看次数

为什么我的结构不够长寿?

在Rust中,我收到以下错误:

<anon>:14:9: 14:17 error: `mystruct` does not live long enough
<anon>:14         mystruct.update();
                  ^~~~~~~~
<anon>:10:5: 17:6 note: reference must be valid for the lifetime 'a as defined on the block at 10:4...
<anon>:10     {
<anon>:11         let initial = vec![Box::new(1), Box::new(2)];
<anon>:12         let mystruct = MyStruct { v : initial, p : &arg };
<anon>:13         
<anon>:14         mystruct.update();
<anon>:15         
          ...
<anon>:12:59: 17:6 note: ...but borrowed value is only valid for the block suffix following statement 1 at 12:58
<anon>:12         let mystruct = MyStruct …
Run Code Online (Sandbox Code Playgroud)

lifetime rust

5
推荐指数
1
解决办法
517
查看次数

标签 统计

rust ×3

error-handling ×1

lifetime ×1