简体   繁体   English

在Rust中,“as”是一个运营商吗?

[英]In Rust, is “as” an operator?

The Rust Reference presently says the following about the as operator : Rust Reference目前as运算符说如下:

7.2.12.5 Type cast expressions 7.2.12.5类型转换表达式

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表达式会将左侧的值转换为右侧的类型。

An example of an as expression: 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 Operator precedence 7.2.12.8运算符优先级

The precedence of Rust binary operators is ordered as follows, going from strong to weak: Rust二元运算符的优先级按如下顺序排列,从强到弱:

 as * / % + - << >> 

)

Naïvely using this as an operator doesn't seem to work: 天真地使用它作为运算符似乎不起作用:

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

Doesn't actually compile: 实际上没有编译:

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

With parentheses — let x = (100 as u16) << 8; 括号 - let x = (100 as u16) << 8; — it compiles. - 它编译。 The parens aren't required in the example in the reference, but seem to be here. 参考中的示例中不需要parens,但似乎在这里。 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? 或者我只是做错了什么?

It is a bit weird that this is called an operator, as the RHS would seem to need to be a type, and typically, I think of an operator as taking two expressions… 这被称为运算符有点奇怪,因为RHS似乎需要是一个类型,通常,我认为运算符采用两个表达式......

The trick here is as takes a type on its right hand side, ie the grammar of as looks something like: is expression 'as' type . 这里的技巧是as需要一种在其右侧,即语法as看起来像:为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> ). as之后的表达式看起来有点像(一个类型的开头),它试图解析u16<<...好像u16有一个类型参数(一个带有类似前缀的类型的例子就是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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM