mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-23 12:39:42 +00:00
Merge pull request #240 from Lmmmmmm-bb/chore/panic
chore: solution of panic second question
This commit is contained in:
@ -25,18 +25,20 @@ fn main() {
|
|||||||
```rust
|
```rust
|
||||||
// MAKE the code work by fixing all panics
|
// MAKE the code work by fixing all panics
|
||||||
fn main() {
|
fn main() {
|
||||||
assert_eq!("abc".as_bytes(), [96, 97, 98]);
|
assert_eq!("abc".as_bytes(), [97, 98, 99]);
|
||||||
|
|
||||||
let v = vec![1, 2, 3];
|
let v = vec![1, 2, 3];
|
||||||
let ele = v[3];
|
let ele = v[2];
|
||||||
// unwrap may panic when get return a None
|
// unwrap may panic when get return a None
|
||||||
let ele = v.get(3).unwrap();
|
let ele = v.get(2).unwrap();
|
||||||
|
|
||||||
// Sometimes, the compiler is unable to find the overflow errors for you in compile time ,so a panic will occur
|
// Sometimes, the compiler is unable to find the overflow errors for you in compile time ,so a panic will occur
|
||||||
let v = production_rate_per_hour(2);
|
let v = production_rate_per_hour(2);
|
||||||
|
|
||||||
// because of the same reason as above, we have to wrap it in a function to make the panic occur
|
// because of the same reason as above, we have to wrap it in a function to make the panic occur
|
||||||
divide(15, 0)
|
divide(15, 1);
|
||||||
|
|
||||||
|
println!("Success!")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn divide(x:u8, y:u8) {
|
fn divide(x:u8, y:u8) {
|
||||||
@ -44,7 +46,7 @@ fn divide(x:u8, y:u8) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn production_rate_per_hour(speed: u8) -> f64 {
|
fn production_rate_per_hour(speed: u8) -> f64 {
|
||||||
let cph: u8 = 221;
|
let cph: u8 = 21;
|
||||||
match speed {
|
match speed {
|
||||||
1..=4 => (speed * cph) as f64,
|
1..=4 => (speed * cph) as f64,
|
||||||
5..=8 => (speed * cph) as f64 * 0.9,
|
5..=8 => (speed * cph) as f64 * 0.9,
|
||||||
|
Reference in New Issue
Block a user