Julia Result Patterns
A result pattern is a small value that holds either a good value or an error note. The caller checks the note instead of catching an exception.
A Result holds a value and an error note
The success case holds 42 with an empty note. The check on the note prints true.
struct Result
value::Int
error::String
end
ok = Result(42, "")
println(ok.value)
println(ok.error == "")The error case fills the note
The failure case holds 0 with the note missing. The note itself is printed.
struct Result
value::Int
error::String
end
bad = Result(0, "missing")
println(bad.error)An unwrap helper returns the value or a fallback
The helper returns 42 for the success case. It returns 7 for the failure case.
struct Result
value::Int
error::String
end
function unwrap(r)
if r.error == ""
return r.value
end
return 7
end
println(unwrap(Result(42, "")))
println(unwrap(Result(0, "missing")))Example
struct Result
value::Int
error::String
end
function unwrap(r)
if r.error == ""
return r.value
end
return 7
end
function half_result(x)
if x < 0
return Result(0, "negative")
end
return Result(div(x, 2), "")
end
println(unwrap(half_result(20)))
println(unwrap(half_result(-4)))Key points
- Result: a small struct holding a value field and an error field.
- Success: an empty error note means the value field holds the answer.
- Failure: a filled error note means the value field holds no answer.
- Unwrap: a helper that returns the value field or a fixed fallback.
- Fallback: a fixed value used when the error note is filled.
In this example, half_result returns a Result holding 10 for 20, so unwrap prints 10. For -4 it returns a Result with the note negative, so unwrap prints the fallback 7.
Note
the caller checks the error note with a plain if, not with a catch.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
unwrap is called on Result(0, "missing"). The fallback is 7. What does unwrap return?