在Rust中,“按"表示操作员? [英] In Rust, is "as" an operator?

查看:109
本文介绍了在Rust中,“按"表示操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust参考目前对 as运算符:

The Rust Reference presently says the following about the as operator:

7.2.12.5类型转换表达式

类型转换表达式用二进制运算符as表示.

7.2.12.5 Type cast expressions

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

执行as表达式会将左侧的值强制转换为右侧的类型.

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

as表达式的示例:

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

(此外,因为这将是相关的:

(Also, since it will be relevant:

7.2.12.8运算符优先级

Rust二进制运算符的优先级按从强到弱的顺序排列:

7.2.12.8 Operator precedence

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

as
* / %
+ -
<< >>

)

单纯地将其用作运算符似乎无效:

Naïvely using this as an operator doesn't seem to work:

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;-进行编译.参考中的示例中不需要括号,但似乎在这里.这里的确切语法是什么?除非这是=的唯一权利,否则是否需要括号?还是我只是做错了什么?

With parentheses — let x = (100 as u16) << 8; — it compiles. The parens aren't required in the example in the reference, but seem to be here. What's the exact syntax here? Are parentheses required unless this is the only thing right of an =? Or am I just doing something wrong?

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

推荐答案

此处的窍门是as在其右侧使用类型,即as的语法类似于:is expression 'as' type. as之后的表达式看起来有点像类型的开始,它试图解析u16<<...,就像u16拥有类型参数一样(例如,带有前缀的类型示例为).

The trick here is as takes a type on its right hand side, i.e. the grammar of as looks something like: is expression 'as' type. The expression after the as looks a bit like (the start of) a type, it's trying to parse u16<<... as if u16 had a type parameter (an example of a type with a prefix like that would be Foo<<T>::Bar>).

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

This is basically just behaviour particular to << because it looks like the type parameter delimiters. If one uses an operator that can't appear after the leading identifier in a type, it works fine:

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

这篇关于在Rust中,“按"表示操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆