This article needs additional citations for verification .(January 2021) |
In functional programming, a result type is a monadic type holding a returned value or an error code. They provide an elegant way of handling errors, without resorting to exception handling; when a function that may fail returns a result type, the programmer is forced to consider success or failure paths, before getting access to the expected result; this eliminates the possibility of an erroneous programmer assumption.
typeResultev=Okv|Erre
. [1] Either
type is used for this purpose, which is defined by the standard library as dataEitherab=Lefta|Rightb
, where a
is the error type and b
is the return type. [2] valueclassResult<outT>
. [3] type('a,'b)result=Okof'a|Errorof'btype
. [4] enumResult<T,E>{Ok(T),Err(E)}
. [5] [6] Either
type, [7] however Scala also has more conventional exception handling.@frozenenumResult<Success,Failure>whereFailure:Error
. [8] std::expected<T,E>
. [9] !T
as the return type of a function. For example fn my_function() !string { ... }
. Error Handling in V.The result object has the methods is_ok()
and is_err()
.
constCAT_FOUND: bool=true;fnmain(){letresult=pet_cat();ifresult.is_ok(){println!("Great, we could pet the cat!");}else{println!("Oh no, we couldn't pet the cat!");}}fnpet_cat()-> Result<(),String>{ifCAT_FOUND{Ok(())}else{Err(String::from("the cat is nowhere to be found"))}}
The Error
type is an interface for iError
.
constcat_found=truefnmain(){cat_name:=get_pet_cat_name()or{println("Oh no, we couldn't pet the cat!")exit(1)}println('Great,wecouldpetthecat'+cat_name)}fnget_pet_cat_name()!string{ifcat_found{return'Max'}else{returnerror('thecatisnowheretobefound')}}