tl;dr在 Rust 中,是否存在“强”类型别名(或类型机制),使得rustc编译器会拒绝(发出错误)可能是相同底层类型的混淆?
目前,可以定义相同底层类型的类型别名
type WidgetCounter = usize;
type FoobarTally = usize;
Run Code Online (Sandbox Code Playgroud)
但是,如果我错误地混淆了两种类型别名的实例,编译器不会拒绝(发出错误或警告)。
fn tally_the_foos(tally: FoobarTally) -> FoobarTally {
// ...
tally
}
fn main() {
let wc: WidgetCounter = 33;
let ft: FoobarTally = 1;
// whoops, passed the wrong variable!
let tally_total = tally_the_foos(wc);
}
Run Code Online (Sandbox Code Playgroud)
(铁锈游乐场)
我希望有一个额外的关键字之类的东西strong
strong type WidgetCounter = usize;
strong type FoobarTally = usize;
Run Code Online (Sandbox Code Playgroud)
这样前面的代码在编译时会导致编译器错误:
error[E4444]: mismatched strong alias type WidgetCounter,
expected a FoobarTally
Run Code Online (Sandbox Code Playgroud)
或者也许 s …