首页 > 关于rust的fs标准库导入和引用

关于rust的fs标准库导入和引用

各位学习rust的朋友,我在按照官方的文档试rust的标准fs库时遇到下面的问题:

rust 1.4.0 stable win7 64位

尝试fs库的时候,如下代码编译报错

   use std::io::prelude::*;
    // use std::io::write_all;
    use std::fs::File;
    
    fn main() {
        let mut f File::create("test.txt");
        f.wirte_all(b"hello");
    }

报错信息:
main.rs:7:4: 7:23 error: no method named wirte_all found for type core::result::Result<std::fs::File, std::io::error::Error> in the current scope
main.rs:7 f.wirte_all(b"hello");

            ^~~~~~~~~~~~~~~~~~~

error: aborting due to previous error
Could not compile test.



各位知道是什么原因么?




大哥,你打字打错了, 不是wirte_all, 是write_all


报错信息写得很清楚了,类型不匹配!

File::create("test.txt")返回值的类型是core::result::Result<std::fs::File, std::io::error::Error>

所以你需要做一个match


fn main() {
    let mut file = File::create('foo.txt');
    
    match file {
        Ok(mut stream) => {
            stream.write_all(b"bar");
        }
        Err(err) => {
            panic!(err);
        }
    }
}
【热门文章】
【热门文章】