我有一个枚举:
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) 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)