Search code examples
typescriptfunctionrusttypesparameters

Rust literal function parameters


I have been trying to understand if it is possible to provide literals as function parameter types.

This is something I do quite frequently with Typescript and was wondering if there is a way to do this in rust. e.g.

function example(param: 1 | 2) { }

example(1); // OK
example(2); // OK
example(3); // Type Error

or better yet.


const FLAGS = {
    a: 1,
    b: 2,
} as const;

export type ValueOf<T> = T[keyof T];

function example(flag: ValueOf<typeof FLAGS>) {}

example(FLAGS.a); // OK
example(1);       // OK
example(FLAGS.b); // OK
example(2);       // OK
example(3);       // Type Error

Solution

  • This can be accomplished using enums as stated in @David Fong's comment.

    example from rust book.

    enum Coin {
        Penny,
        Nickel,
        Dime,
        Quarter,
    }
    
    fn value_in_cents(coin: Coin) -> u8 {
        match coin {
            Coin::Penny => 1,
            Coin::Nickel => 5,
            Coin::Dime => 10,
            Coin::Quarter => 25,
        }
    }