Motoko Compilation Error - M0116

:police_car_light: Help Needed: Motoko Compilation Error - M0116

Hey everyone! Working on a project and stuck on a persistent Motoko compilation error. Any help would be greatly appreciated! :folded_hands:

Error:

variant pattern cannot consume expected type Principal Motoko(M0116)

Code causing the issue:

private func generateMockCanisterId() : Principal {
    let mockId = "rdmx6-jaaaa-aaaah-qcaiq-cai";
    switch (Principal.fromText(mockId)) {
        case (#ok principal) principal;
        case (#err _) Principal.fromBlob(Blob.fromArray([1, 2, 3, 4, 5]));
    }
};

What we’ve tried:
:white_check_mark: Fixed pattern matching syntax (removed parentheses)
:white_check_mark: Updated dfx.json configuration
:white_check_mark: Verified file structure and imports
:white_check_mark: Tested with both #ok(principal) and #ok principal patterns
:white_check_mark: Checked Result type usage (lowercase #ok/#err vs uppercase #Ok/#Err)

Project Context:

  • DFX version: 0.26.1
  • Building a Motoko backend canister
  • Error occurs during dfx build autopilot_backend
  • Files are properly structured in src/autopilot-icp-backend/

The error specifically points to the Principal destructuring in the pattern match. Is there something specific about Principal type handling in pattern matching that we’re missing?

Full error output:

/path/to/deploy.mo:70.23-70.37: type error [M0116], variant pattern cannot consume expected type Principal

Any insights on what might be causing this? Thanks in advance! :rocket:

Motoko #help #compilation-error dfx #icp

I just checked that Principal.fromText does not return a result, you don’t need a pattern match on it.

Right! The signature is

Principal.fromText : Text -> Principal

This one has always been a bit of an issue because a user can provide invalid text and this will trap. I think on mops there is a principle-ext that has a version that returns ?Principal if you need that. (This should be in new base if it isn’t already)

2 Likes