Parse input with Result
This recipe calls Go's strconv.Atoi, propagates its raw (int, error) result with postfix ?, and adds an application-level range check.
Prerequisites
keikaand a supported Go toolchain onPATH- one empty working directory
Project tree
text
port-parser/
└── main.kmSource
Save as main.km:
ts
import go fmt from "fmt";
import go strconv from "strconv";
function parsePort(text: string): Result<int> {
const port = strconv.Atoi(text)?;
if (port < 1 || port > 65535) {
return fail(fmt.Errorf("port out of range: %d", port));
}
return ok(port);
}
function main(): void {
const [port, portErr] = parsePort("8080");
fmt.Println(port, portErr === nil);
const [invalid, invalidErr] = parsePort("70000");
fmt.Println(invalid, invalidErr !== nil);
}Check and run
sh
keika check main.km
keika run main.kmExpected output:
text
8080 true
0 trueThe first call succeeds. The second returns the int zero value plus a non-nil error because 70000 is outside the accepted port range.
Contract demonstrated
strconv.Atoi(text)?evaluates once and propagates a non-nil Go error.fail(err)emits the payload type's zero value and the error.Result<int>lowers directly to Go(int, error).[value, err]keeps the two results explicit at the call site.
To inspect the exact error rather than only its presence, call err.Error() inside a branch where err !== nil is known.
See Errors and nullability for storage restrictions and exception separation.