Created
April 1, 2022 05:48
-
-
Save hussachai/dff06ce3a09acd704ed55f9f6e8d994d to your computer and use it in GitHub Desktop.
Error Handling in Rust that Every Beginner should Know (Go way)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func square(s string) (float64, error) { | |
i, e := strconv.ParseFloat(s, 64) | |
return i * i, e | |
} | |
func calculate(x string, y string) (*float64, error) { | |
x2, e := square(x) | |
if e != nil { | |
return nil, e | |
} | |
y2, e := square(y) | |
if e != nil { | |
return nil, e | |
} | |
r := math.Sqrt(x2 + y2) | |
return &r, nil | |
} | |
r, _ := calculate("2", "2") | |
println(*r) // +2.828427e+000 | |
_, e := calculate("2", "?") | |
println(e.Error()) // strconv.ParseFloat: parsing "?": invalid syntax |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment