Skip to content

Instantly share code, notes, and snippets.

@hussachai
Created April 1, 2022 05:48
Show Gist options
  • Save hussachai/dff06ce3a09acd704ed55f9f6e8d994d to your computer and use it in GitHub Desktop.
Save hussachai/dff06ce3a09acd704ed55f9f6e8d994d to your computer and use it in GitHub Desktop.
Error Handling in Rust that Every Beginner should Know (Go way)
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