πForce-Statements
Force-Statement Syntax
let <successVar>, <failureVar> = force <expr> with <expr>
A force-statement evaluates the expr
between force
and with
. It must evaluate to (..., error)
.
If
error != nil
:The program will panic with the
expr
to the right ofwith
If
error == nil
:expression between
try
andwith
will be destructured intosuccessVar
andfailureVar
Working Example
The below code will error, which is intended since force
will call panic
package main
import "fmt" as fmt
import "errors" as errors
fun divide(num1: Int, num2: Int): (Int, Error) {
if num2 == 0 {
return (0, errors.new("Cannot divide by 0"))
}
return (num1 / num2, null)
}
fun divideBy2(num: Int): (Int, Error) {
return divide(num, 2)
}
fun divideBy0(num: Int): (Int, Error) {
return divide(num, 0)
}
fun getResults(num: Int): (Int, Error) {
let dBy2Res, dBy2Err = force divideBy2(5) with "Error when dividing 5 by 2"
let dBy0Res, dBy0Err = force divideBy0(10) with "Error when dividing 10 by 0"
return (dBy2Res + dBy0Res, null)
}
fun main(): Unit {
fmt.println("Let's see if there's an error:")
let res, err = getResults(10)
fmt.println(err != null)
}
Last updated