The Rust Reference presently says the following about 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 }
(Also, since it will be relevant:
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;
}
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;
— 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?
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…