以下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) 我试图迭代一个字符串向量的子部分,即一个子部分Vec<String>.在每次迭代中,我想将字符串作为切片传递给函数.
我没有注意到Vec::get返回一个Option,并认为我可以直接迭代返回值:
fn take_str(s: &str) {
println!("{}", s);
}
fn main() {
let str_vec: Vec<String> =
["one", "two", "three", "uno", "dos", "tres"].iter().map(|&s|
s.into()).collect();
for s in str_vec.get(0..3) {
take_str(&s); // Type mismatch: found type `&&[std::string::String]`
}
}
Run Code Online (Sandbox Code Playgroud)
显然,我期待s成为一个String,但事实上&[String].这是因为我的for循环实际上是迭代Option返回的Vec::get().
我还编写了以下代码,它演示了for循环实际上解开了Option:
let foo = Option::Some ( ["foo".to_string()] );
for f in foo {
take_str(&f); // Same error as above, showing `f` is …Run Code Online (Sandbox Code Playgroud) 我正在尝试根据Option函数的输入切换行为.想法是基于给定Option是否存在来迭代.这是一个最小的,如果愚蠢的例子:
use std::iter;
fn main() {
let x: Option<i64> = None;
// Repeat x 5 times if present, otherwise count from 1 to 5
for i in match x {
None => 1..5,
Some(x) => iter::repeat(x).take(5),
} {
println!("{}", i);
}
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
error[E0308]: match arms have incompatible types
--> src/main.rs:7:14
|
7 | for i in match x {
| ______________^
8 | | None => 1..5,
9 | | Some(x) => iter::repeat(x).take(5),
| | …Run Code Online (Sandbox Code Playgroud) 我正在尝试继续Option<Vec<>>.
#[derive(Debug)]
pub struct Person {
pub name: Option<String>,
pub age: Option<u64>,
}
#[derive(Debug)]
pub struct Foo {
pub people: Option<Vec<Person>>,
}
Run Code Online (Sandbox Code Playgroud)
天真的我正在使用
for i in foo.people.iter() {
println!("{:?}", i);
}
Run Code Online (Sandbox Code Playgroud)
Vec我没有遍历所有元素,而是实际显示整体Vec.这就像我在迭代唯一的参考Option.
使用以下内容,我正在迭代Vec内容:
for i in foo.people.iter() {
for j in i.iter() {
println!("{:?}", j);
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定这是最令人愉快的语法,我相信你应该解开第Option一个实际迭代的集合.
Option::iter如果你总是有一个参考,那么我看不到你实际可以使用的地方.
这是游乐场的链接.