Parttern Matching issue with text variables in motoko

I have this piece of code that returns an error

this pattern is never matched

There are two variables defined

let Get = "GET";
let Post = "POST";

I defined switch cases for both variables, but the first variable matches every text instead of the assigned text. This is an issue because it blocks the code from going to the other switch cases.

switch (method){
    case (Get){
        ...
    };
    case (Post){ // this pattern is never matched
        ...
    };
}

However, It works when I create switch cases with raw text instead of with variables.

switch (method){
    case ("GET"){
        ...
    };
    case ("POST"){
        ...
    };
}

Is this a bug, or was this the intended design choice for Motoko?

I think it’s a bug in the sense that your code contains something you probably didn’t intend, and the compiler error is informing you of that.

When you write case (Get) you aren’t comparing method with the previous binding of Get but instead are creating a new binding called Get which contains all of the possible values of method.

See: Language quick reference | Internet Computer Developer Portal

I’m not sure how to do what you intended if you don’t want to use the literal pattern. Your only option might be to use if method == Get.

2 Likes