ElliotSaha
ElliotSaha

Reputation: 51

Does Rust have a way to restrict string types to specific values (string literal types)?

In Typescript, there are ways to type a value so it can have only be a specific string

e.g.

type example = "hello" | "world";

Am I limited to only the "String" type in rust or is there a way to narrow them down like there is in Typescript?

Right now I have:

pub struct ButtonProps {
    pub color: String
}

But color could be anything, I want it only to be "primary" or "secondary"

How would I go about doing this?

Upvotes: 2

Views: 607

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70277

No, there's no equivalent feature in Rust. We would simply use an enum in Rust to accomplish the same.

#[derive(Copy, Clone, ...)]
pub enum ButtonPropsColor { Hello, World }

pub struct ButtonProps {
  pub color: ButtonPropsColor,
}

Then, if you like, you can write conversion functions to get from String to ButtonPropsColor and vice versa.

impl From<&str> for ButtonPropsColor {
  fn from(s: &str) -> ButtonPropsColor {
    ...
  }
}

impl From<ButtonPropsColor> for String {
  fn from(s: ButtonPropsColor) -> String {
    ...
  }
}

Upvotes: 7

Related Questions