I am using the results library (https://github.com/arnetheduck/nim-results)
This is the function
proc getValue(node: ValuesNode, key: Bytes32) : Result[Bytes32, string] =
## Returns the value stored at the given `key`
if node.values[key[^1]] == nil:
return err("Value not found")
else:
return cast[Bytes32](node.values[key[^1]])
I simply want to return the Bytes32 type if everything is correct else return an error but I am not able to return the Bytes32 value
You are missing the ok in the success path:
proc getValue(node: ValuesNode, key: Bytes32) : Result[Bytes32, string] =
if node.values[key[^1]] == nil:
err("Value not found")
else:
ok(cast[Bytes32](node.values[key[^1]]))
(took the liberty to remove the returns, but that is not necessary)
i've been working with a Result clone written on top of std::expected, and, while i miss pretty much everything else about nim-result, ive grown to enjoy being able to return a bare T from a function returning Result[T,E]
#include <expected>
#include <string>
using err_t = std::string;
template<class T> using Result = std::expected<T,err_t>;
using err = std::unexpected<err_t>;
Result<int> foo(bool x){
if (x)
return err("oh noes");
else
return 5;
}
if you've got a standard error type in your project like
type R[T] = Result[T,string]
then you can have that implicit conversion, too, for good or ill, with
converter toR[T](x:T):R[T] = ok(x)
proc foo(x:bool):Result[int,string] =
if x:
err("oh noes")
else:
5
but embracing strict typing is more the Nim way