在 Rust 中,"as" 是运算符吗?

In Rust, is "as" an operator?

Rust 参考目前对 the as operator 的描述如下:

7.2.12.5 Type cast expressions

A type cast expression is denoted with the binary operator as.

Executing an as expression casts the value on the left-hand side to the type on the right-hand side.

An example of an as expression:

fn average(values: &[f64]) -> f64 {
  let sum: f64 = sum(values);
  let size: f64 = len(values) as f64;
  sum / size
}

(此外,因为它是相关的:

7.2.12.8 Operator precedence

The precedence of Rust binary operators is ordered as follows, going from strong to weak:

as
* / %
+ -
<< >>

)

天真地将其用作运算符似乎行不通:

fn main() {
    let x = 100 as u16 << 8;
}

实际上没有编译:

% rustc testing.rs
testing.rs:2:24: 2:25 error: expected type, found `8`
testing.rs:2    let x = 100 as u16 << 8;

带括号 - let x = (100 as u16) << 8; - 它编译。参考文献中的示例不需要括号,但似乎在这里。这里的确切语法是什么?除非这是 = 的唯一权利,否则是否需要括号?还是我做错了什么?

这被称为运算符有点奇怪,因为 RHS 似乎需要是一种类型,通常,我认为运算符采用两个表达式......

这里的技巧是 as 在其右侧采用类型,即 as 的语法类似于:is expression 'as' typeas 之后的表达式看起来有点像一个类型的(开始),它试图解析 u16<<... 就好像 u16 有一个类型参数(一个带有前缀的类型的例子就像那样 Foo<<T>::Bar>).

这基本上只是 << 特有的行为,因为它看起来像类型参数定界符。如果使用不能出现在类型中前导标识符之后的运算符,它可以正常工作:

fn main() {
    let x = 100 as u16 - 8;
}