将字符串的值限制为 Rust 中的某个集合

Restrict the values of a string to a certain set in rust

如何在 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.

rust 中的等价物是什么

您将为您的角色使用 enum,然后使用序列化方法(例如使用 strumserde)来解析任何字符串输入并验证它们是否可以应用。

这是一个使用扫弦的例子:



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);