How to type literal string input params

Can a function expect a type of argument that is either "kung" | "foo", how is this done in Rust?
Some API's allow only specific strings to be used. How can I enforce this in rust?

Use an enum.

enum KungFoo { Kung, Foo }
fn bar(kf: KungFoo) { ... }

If, for some reason, you need the actual strings, add a method to get them:

impl KungFoo {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Kung => "kung",
            Self::Foo => "foo",
        }
    }
}
1 Like

thanks, but now it is a problem if the string starts with a number, it won't compile.

Use a different name, or prefix with a letter, like "2score" => N2Score.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.