Home > Software engineering >  Restrict the values of a string to a certain set in rust
Restrict the values of a string to a certain set in rust

Time:04-13

how do I restrict the vales of a string to a certain set in rust?

// string literal union type with
// values of "admin", "owner", "user"
type Roles = "admin" | "owner" | "user";

// use the type "Roles" for the "role" variable
let role: Roles;

// assing a value other than "admin", "owner", "user"
role = "Hello World!"; // ❌ not allowed. Type '"Hello World!"' is not assignable to type 'Roles'

// assign a valid string value
role = "admin"; // ✅ allowed.

what is the equivalent in rust

CodePudding user response:

You would use an enum for your roles, and then use a serialization method (e.g. using strum or serde) to parse any string inputs and verify that they can be applied.

Here's an example using strum:



use std::str::FromStr;
use strum_macros::EnumString;

#[derive(Debug, PartialEq, EnumString)]
#[strum(ascii_case_insensitive)]
enum Role {
    Admin,
    Owner,
    User,
}

// tests
let admin = Role::from_str("admin").unwrap();
assert_eq!(Role::Admin, admin);

  • Related