相关疑难解决方法(0)

为什么要试试!()和?在不返回Option或Result的函数中使用时不编译?

为什么这段代码不能编译?

use std::{fs, path::Path};

fn main() {
    let dir = Path::new("../FileSystem");

    if !dir.is_dir() {
        println!("Is not a directory");
        return;
    }

    for item in try!(fs::read_dir(dir)) {
        let file = match item {
            Err(e) => {
                println!("Error: {}", e);
                return;
            }
            Ok(f) => f,
        };

        println!("");
    }

    println!("Done");
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

error[E0308]: mismatched types
  --> src/main.rs:11:17
   |
11 |     for item in try!(fs::read_dir(dir)) {
   |                 ^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
   |
   = note: expected type `()`
              found type `std::result::Result<_, _>`
   = note: …
Run Code Online (Sandbox Code Playgroud)

rust

42
推荐指数
2
解决办法
7977
查看次数

为什么`Option`支持`IntoIterator`?

我试图迭代一个字符串向量的子部分,即一个子部分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)

foreach optional rust

12
推荐指数
1
解决办法
483
查看次数

Rust File示例无法编译

Rust 文件示例似乎没有使用Rust 1.18.0编译.

对于例如:

use std::fs::File;
use std::io::prelude::*;
fn main() {
    let mut file = File::open("foo.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    assert_eq!(contents, "Hello, world!");
}
Run Code Online (Sandbox Code Playgroud)

错误日志:

rustc 1.18.0 (03fc9d622 2017-06-06)
error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied
 --> <anon>:4:20
  |
4 |     let mut file = File::open("foo.txt")?;
  |                    ----------------------
  |                    |
  |                    the trait `std::ops::Carrier` is not implemented for `()`
  |                    in this macro invocation
  |
  = note: required by `std::ops::Carrier::from_error`

error[E0277]: the …
Run Code Online (Sandbox Code Playgroud)

rust

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

标签 统计

rust ×3

foreach ×1

optional ×1