小编Ole*_*osh的帖子

如何确保在编译时可以从特定函数返回每个枚举变量?

我有一个枚举:

enum Operation {
    Add,
    Subtract,
}

impl Operation {
    fn from(s: &str) -> Result<Self, &str> {
        match s {
            "+" => Ok(Self::Add),
            "-" => Ok(Self::Subtract),
            _ => Err("Invalid operation"),
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想确保在编译时在from函数中处理每个枚举变量。

我为什么需要这个?例如,我可能添加一个Product操作而忘记在from函数中处理这种情况:

enum Operation {
    // ...
    Product,
}

impl Operation {
    fn from(s: &str) -> Result<Self, &str> {
        // No changes, I forgot to add a match arm for `Product.
        match s {
            "+" => Ok(Self::Add),
            "-" => Ok(Self::Subtract),
            _ …
Run Code Online (Sandbox Code Playgroud)

enums rust

7
推荐指数
2
解决办法
847
查看次数

Typescript subtract two numbers at compile time

Original question

I need an utility type Subtract<A, B> where A and B are numbers. For example:

type Subtract<A extends number, B extends number> = /* implementation */ 
const one: Subtract<2, 1> = 1
const two: Subtract<4, 2> = 2
const error: Subtract<2, 1> = 123 // Error here: 123 is not assignable to type '1'.
Run Code Online (Sandbox Code Playgroud)

Arguments to the Subtract<A, B> are always number literals or compile time constants. I do not need

let foo: Subtract<number, number> // 'foo' may …
Run Code Online (Sandbox Code Playgroud)

typescript typescript-generics

4
推荐指数
1
解决办法
144
查看次数

标签 统计

enums ×1

rust ×1

typescript ×1

typescript-generics ×1