[profile.release] panic = 'abort'
//src/main.rs fn main() { panic!("crash and burn"); }
$ cargo run Compiling panic v0.1.0 (file:///projects/panic) Finished dev [unoptimized + debuginfo] target(s) in 0.25s Running `target/debug/panic` thread 'main' panicked at 'crash and burn', src/main.rs:2:5 note : run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
//src/main.rs fn main() { let v = vec![1, 2, 3]; v[99]; }
$ cargo run Compiling panic v0.1.0 (file:///projects/panic) Finished dev [unoptimized + debuginfo] target(s) in 0.27s Running `target/debug/panic` thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libcore/slice/mod.rs:2806:10 note : run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
※ Only works in debug mode
$ RUST_BACKTRACE=1 cargo run thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libcore/slice/mod.rs:2806:10 stack backtrace: 0: backtrace::backtrace::libunwind::trace at /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/libunwind.rs:88 1: backtrace::backtrace::trace_unsynchronized at /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/mod.rs:66 2: std::sys_common::backtrace::_print_fmt at src/libstd/sys_common/backtrace.rs:84 3: <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt at src/libstd/sys_common/backtrace.rs:61 4: core::fmt::ArgumentV1::show_usize 5: std::io::Write::write_fmt at src/libstd/io/mod.rs:1426 6: std::sys_common::backtrace::_print at src/libstd/sys_common/backtrace.rs:65 7: std::sys_common::backtrace::print at src/libstd/sys_common/backtrace.rs:50 8: std::panicking::default_hook::{{closure}} at src/libstd/panicking.rs:193 9: std::panicking::default_hook at src/libstd/panicking.rs:210 10: std::panicking::rust_panic_with_hook at src/libstd/panicking.rs:471 11: rust_begin_unwind at src/libstd/panicking.rs:375 12: core::panicking::panic_fmt at src/libcore/panicking.rs:84 13: core::panicking::panic_bounds_check at src/libcore/panicking.rs:62 14: <usize as core::slice::SliceIndex<[T]>>::index at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libcore/slice/mod.rs:2806 15: core::slice::<impl core::ops::index::Index<I> for [T]>::index at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libcore/slice/mod.rs:2657 16: <alloc::vec::Vec<T> as core::ops::index::Index<I>>::index at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/liballoc/vec.rs:1871 17: panic::main at src/main.rs:4 18: std::rt::lang_start::{{closure}} at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libstd/rt.rs:67 19: std::rt::lang_start_internal::{{closure}} at src/libstd/rt.rs:52 20: std::panicking::try::do_call at src/libstd/panicking.rs:292 21: __rust_maybe_catch_panic at src/libpanic_unwind/lib.rs:78 22: std::panicking::try at src/libstd/panicking.rs:270 23: std::panic::catch_unwind at src/libstd/panic.rs:394 24: std::rt::lang_start_internal at src/libstd/rt.rs:51 25: std::rt::lang_start at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libstd/rt.rs:67 26: panic::main
enum Result<T, E> { Ok(T), // variant for success; T type returned for success Err(E), // variant for failure; E type of error returned for failure }
//src/main.rs use std::fs::File; fn main() { let f = File::open("hello.txt"); }
//src/main.rs use std::fs::File; fn main() { let f: u32 = File::open("hello.txt"); }
$ cargo run Compiling error-handling v0.1.0 (file:///projects/error-handling) error[E0308]: mismatched types --> src/main.rs:4:18 | 4 | let f: u32 = File::open("hello.txt"); | --- ^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`, found enum `std::result::Result` | | | expected due to this | = note: expected type `u32` found enum `std::result::Result<std::fs::File, std::io::Error>` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. error: could not compile `error-handling`. To learn more, run the command again with --verbose.
//src/main.rs use std::fs::File; fn main() { let f = File::open("hello.txt"); let f = match f { Ok(file) => file, Err(error) => panic!("Problem opening the file: {:?}", error), }; }
$ cargo run Compiling error-handling v0.1.0 (file:///projects/error-handling) Finished dev [unoptimized + debuginfo] target(s) in 0.73s Running `target/debug/error-handling` thread 'main' panicked at 'Problem opening the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:8:23 note : run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
//src/main.rs use std::fs::File; use std::io::ErrorKind; fn main() { let f = File::open("hello.txt"); let f = match f { Ok(file) => file, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("hello.txt") { Ok(fc) => fc, Err(e) => panic!("Problem creating the file: {:?}", e), }, other_error => { panic!("Problem opening the file: {:?}", other_error) } }, }; }
//src/main.rs use std::fs::File; fn main() { let f = File::open("hello.txt").unwrap(); }
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', src/libcore/result.rs:906:4
//src/main.rs use std::fs::File; fn main() { let f = File::open("hello.txt").expect("Failed to open hello.txt"); }
thread 'main' panicked at 'Failed to open hello.txt: Error { repr: Os { code: 2, message: "No such file or directory" } }', src/libcore/result.rs:906:4
//src/main.rs use std::fs::File; use std::io; use std::io::Read; fn read_username_from_file() -> Result<String, io::Error> { let f = File::open("hello.txt"); let mut f = match f { Ok(file) => file, Err(e) => return Err(e), }; let mut s = String::new(); match f.read_to_string(&mut s) { Ok(_) => Ok(s), Err(e) => Err(e), } }
//src/main.rs use std::fs::File; use std::io; use std::io::Read; fn read_username_from_file() -> Result<String, io::Error> { let mut f = File::open("hello.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) }
//src/main.rs use std::fs::File; use std::io; use std::io::Read; fn read_username_from_file() -> Result<String, io::Error> { let mut s = String::new(); File::open("hello.txt")?.read_to_string(&mut s)?; Ok(s) }
//src/main.rs use std::fs; use std::io; fn read_username_from_file() -> Result<String, io::Error> { fs::read_to_string("hello.txt") }
//src/main.rs use std::fs::File; fn main() { let f = File::open("hello.txt")?; }
$ cargo run Compiling error-handling v0.1.0 (file:///projects/error-handling) error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`) --> src/main.rs:4:13 | 3 | / fn main() { 4 | | let f = File::open("hello.txt")?; | | ^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()` 5 | | } | |_- this function should return `Result` or `Option` to accept `?` | = help: the trait `std::ops::Try` is not implemented for `()` = note: required by `std::ops::Try::from_error` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. error: could not compile `error-handling`. To learn more, run the command again with --verbose.
//src/main.rs use std::error::Error; use std::fs::File; fn main() -> Result<(), Box<dyn Error>> { let f = File::open("hello.txt")?; Ok(()) }
//src/main.rs fn main() { use std::net::IpAddr; let home: IpAddr = "127.0.0.1".parse().unwrap(); }
Guessing Game snippet:
loop { // --snip-- let guess: i32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; if guess < 1 || guess > 100 { println!("The secret number will be between 1 and 100."); continue; } match guess.cmp(&secret_number) { // --snip-- }
pub struct Guess { value: i32, } impl Guess { pub fn new(value: i32) -> Guess { if value < 1 || value > 100 { panic!("Guess value must be between 1 and 100, got {}.", value); } Guess { value } } pub fn value(&self) -> i32 { self.value } }