How to use Result function?

I want examples for the Result function. Can anyone help me?

Rust? What is Result function do you mean?

Using Motoko:

  1. declare Type (snippet):
    type Result<T,E> = Result.Result<T,E>;

2.function (snippet):

public shared query ({caller}) func exportStore() : async Result<[(Id, Instruction)],Text> {
        let isAllowed : Bool = Principal.equal(canisterOwner,caller);
        if (isAllowed) {
            #ok(Iter.toArray(instructionsRegistry.entries())); 
        } else {
            #err("Caller isn't allowed to export the store. Caller is : " # Principal.toText(caller));
        }
    };
2 Likes

Why do we need else for Result? I have noticed that it always needs to be provided even if it is followed by a switch statement.

I don’t think you should. If you can share some code where you think this is necessary I might be able to help.

public shared ({caller}) func create_username(username: Username) : async Result.Result<Username, UsernameError> {
    let tags = [ACTOR_NAME, "create_username"];
    let principal : UserPrincipal = Principal.toText(caller);

    let valid_username : Bool = Utils.is_valid_username(username);
    let username_available : Bool = check_username_is_available(username);
    let user_has_username: Bool = check_user_has_a_username(principal);

    if (valid_username == false) {
        #err(#UsernameInvalid);
    };

    if (username_available == false) {
        #err(#UsernameTaken);
    } else {
        if (user_has_username == true) {
            #err(#UserHasUsername);
        } else {
            usernames.put(principal, username);
            username_owners.put(username, principal);

            await Logger.log_event(tags, debug_show("created"));

            #ok(username);
        };
    };
};

type error [M0096], expression of type
{#err : {#UsernameInvalid}}
cannot produce expected type
()

I wanted to have linear execution vs nested if statements. Atleast that is the goal to make it easier to read

You might need to explicitly return, e.g. return #err(#UsernameInvalid);

1 Like

That fixed it. Thanks :slight_smile: