分组表达式
语法
GroupedExpression :
(
表达式)
带括号的表达式 包裹着一个单独的表达式,并求值为该表达式。带括号的表达式的语法是一个 (
,接着是一个表达式(称为封闭操作数),然后是一个 )
。
带括号的表达式求值为封闭操作数的值。与其他表达式不同,带括号的表达式既是位置表达式也是值表达式。当封闭操作数是位置表达式时,它就是位置表达式;当封闭操作数是值表达式时,它就是值表达式。
括号可以用于显式地修改表达式中子表达式的优先级顺序。
带括号的表达式的示例
#![allow(unused)] fn main() { let x: i32 = 2 + 3 * 4; // not parenthesized let y: i32 = (2 + 3) * 4; // parenthesized assert_eq!(x, 14); assert_eq!(y, 20); }
一个必须使用括号的示例是当调用作为结构体成员的函数指针时
#![allow(unused)] fn main() { struct A { f: fn() -> &'static str } impl A { fn f(&self) -> &'static str { "The method f" } } let a = A{f: || "The field f"}; assert_eq!( a.f (), "The method f"); assert_eq!((a.f)(), "The field f"); }