Skip to content

Instantly share code, notes, and snippets.

@hussachai
Last active April 1, 2022 06:02
Show Gist options
  • Save hussachai/c15d374e265baaeec379de6edc7c1fe9 to your computer and use it in GitHub Desktop.
Save hussachai/c15d374e265baaeec379de6edc7c1fe9 to your computer and use it in GitHub Desktop.
Error Handling in Rust that Every Beginner should Know (Scala way)
def square(s: String): Try[Double] = Try {
val i = s.toDouble
i * i
}
def calculate(x: String, y: String): Try[Double] = {
for {
x <- square(x)
y <- square(y)
} yield Math.sqrt(x + y)
}
println(calculate("2", "2")) // Success(2.828)
println(calculate("2", "x")) // Failure(java.lang.NumberFormatException)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment