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 of with
If error == nil:
expression between try and with will be destructured into successVar and failureVar
Working Example
package main
import "fmt" as fmt
import "errors" as errors
fun (Int, Error) divide(Int num1, Int num2) {
if num2 == 0 {
return (0, errors.new("Cannot divide by 0"))
}
return (num1 / num2, null)
}
fun (Int, Error) divideBy2(Int num) {
return divide(num, 2)
}
fun (Int, Error) divideBy0(Int num) {
return divide(num, 0)
}
fun (Int, Error) getResults(Int num) {
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 Unit main() {
fmt.println("Let's see if there's an error:")
let res, err = getResults(10)
fmt.println(err != null)
}
package main
import fmt "fmt"
import errors "errors"
func divide(num1 int, num2 int) (int, error) {
if num2 == 0 {
return 0, errors.New("Cannot divide by 0")
}
return num1 / num2, nil
}
func divideBy2(num int) (int, error) {
return divide(num, 2)
}
func divideBy0(num int) (int, error) {
return divide(num, 0)
}
func getResults(num int) (int, error) {
dBy2Res, dBy2Err := divideBy2(5)
if dBy2Err != nil {
panic("Error when dividing 5 by 2")
}
dBy0Res, dBy0Err := divideBy0(10)
if dBy0Err != nil {
panic("Error when dividing 10 by 0")
}
// Eliminates any 'unused variable' errors
_, _, _, _ = dBy0Err, dBy0Res, dBy2Err, dBy2Res
return dBy2Res + dBy0Res, nil
}
func main() {
fmt.Println("Let's see if there's an error:")
res, err := getResults(10)
fmt.Println(err != nil)
// Eliminates any 'unused variable' errors
_, _ = err, res
}
Let's see if there's an error:
panic: Error when dividing 10 by 0
goroutine 1 [running]:
main.getResults(0x4bc5f8?)
/home/user/projects/gauntlet-lang/GoTesting/sample.go:37 +0x25
main.main()
/home/user/projects/gauntlet-lang/GoTesting/sample.go:48 +0x5a
exit status 2