0

I can't seem to get the example code from the File documentation to work. I added the main function, etc:

use std::io::prelude::*;
use std::fs::File;

fn main(){
    let mut f = try!(File::create("foo.txt"));
    try!(f.write_all(b"Hello, world!"));

    let mut f = try!(File::open("foo.txt"));
    let mut s = String::new();
    try!(f.read_to_string(&mut s));
    assert_eq!(s, "Hello, world!");
}

Gives me these errors:

 file git:(master) ✗ rustc main.rs -o /tmp/rrust.out
<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err (
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
main.rs:5:17: 5:46 note: in this expansion of try! (defined in <std macros>)
<std macros>:5:8: 6:42 help: run `rustc --explain E0308` to see a detailed explanation
<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err (
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
main.rs:6:5: 6:41 note: in this expansion of try! (defined in <std macros>)
<std macros>:5:8: 6:42 help: run `rustc --explain E0308` to see a detailed explanation
<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err (
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
main.rs:8:17: 8:44 note: in this expansion of try! (defined in <std macros>)
<std macros>:5:8: 6:42 help: run `rustc --explain E0308` to see a detailed explanation
<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err (
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
main.rs:10:5: 10:36 note: in this expansion of try! (defined in <std macros>)
<std macros>:5:8: 6:42 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to 4 previous errors

It looks to me like it really doesn't like those try! statements. I am using Rust 1.5.0.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
vitiral
  • 8,446
  • 8
  • 29
  • 43

1 Answers1

2

The answer was just to unwrap instead of use try. try is used to bubble up results (which makes sense!)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
vitiral
  • 8,446
  • 8
  • 29
  • 43