附录 B: 运算符和符号

这个附录包含了一个 Rust 语法的词汇表,包括单独出现或在路径、泛型、特征边界、宏、属性、注释、元组和括号上下文中出现的运算符和其他符号。

运算符

表B-1 包含了Rust中的运算符,运算符在上下文中出现的示例,简短的解释,以及该运算符是否可重载。如果运算符是可重载的,将列出用于重载该运算符的相关特征。

表 B-1:运算符

OperatorExampleExplanationOverloadable?
!ident!(...), ident!{...}, ident![...]Macro expansion
!!exprBitwise or logical complementNot
!=expr != exprNonequality comparisonPartialEq
%expr % exprArithmetic remainderRem
%=var %= exprArithmetic remainder and assignmentRemAssign
&&expr, &mut exprBorrow
&&type, &mut type, &'a type, &'a mut typeBorrowed pointer type
&expr & exprBitwise ANDBitAnd
&=var &= exprBitwise AND and assignmentBitAndAssign
&&expr && exprShort-circuiting logical AND
*expr * exprArithmetic multiplicationMul
*=var *= exprArithmetic multiplication and assignmentMulAssign
**exprDereferenceDeref
**const type, *mut typeRaw pointer
+trait + trait, 'a + traitCompound type constraint
+expr + exprArithmetic additionAdd
+=var += exprArithmetic addition and assignmentAddAssign
,expr, exprArgument and element separator
-- exprArithmetic negationNeg
-expr - exprArithmetic subtractionSub
-=var -= exprArithmetic subtraction and assignmentSubAssign
->fn(...) -> type, |…| -> typeFunction and closure return type
.expr.identMember access
...., expr.., ..expr, expr..exprRight-exclusive range literalPartialOrd
..=..=expr, expr..=exprRight-inclusive range literalPartialOrd
....exprStruct literal update syntax
..variant(x, ..), struct_type { x, .. }“And the rest” pattern binding
...expr...expr(Deprecated, use ..= instead) In a pattern: inclusive range pattern
/expr / exprArithmetic divisionDiv
/=var /= exprArithmetic division and assignmentDivAssign
:pat: type, ident: typeConstraints
:ident: exprStruct field initializer
:'a: loop {...}Loop label
;expr;Statement and item terminator
;[...; len]Part of fixed-size array syntax
<<expr << exprLeft-shiftShl
<<=var <<= exprLeft-shift and assignmentShlAssign
<expr < exprLess than comparisonPartialOrd
<=expr <= exprLess than or equal to comparisonPartialOrd
=var = expr, ident = typeAssignment/equivalence
==expr == exprEquality comparisonPartialEq
=>pat => exprPart of match arm syntax
>expr > exprGreater than comparisonPartialOrd
>=expr >= exprGreater than or equal to comparisonPartialOrd
>>expr >> exprRight-shiftShr
>>=var >>= exprRight-shift and assignmentShrAssign
@ident @ patPattern binding
^expr ^ exprBitwise exclusive ORBitXor
^=var ^= exprBitwise exclusive OR and assignmentBitXorAssign
|pat | patPattern alternatives
|expr | exprBitwise ORBitOr
|=var |= exprBitwise OR and assignmentBitOrAssign
||expr || exprShort-circuiting logical OR
?expr?Error propagation

非运算符符号

以下列表包含所有不作为运算符功能的符号;也就是说,它们的行为不像函数或方法调用。

表B-2显示了单独出现并在多种位置有效的符号。

表 B-2:独立语法

SymbolExplanation
'identNamed lifetime or loop label
...u8, ...i32, ...f64, ...usize, etc.Numeric literal of specific type
"..."String literal
r"...", r#"..."#, r##"..."##, etc.Raw string literal, escape characters not processed
b"..."Byte string literal; constructs an array of bytes instead of a string
br"...", br#"..."#, br##"..."##, etc.Raw byte string literal, combination of raw and byte string literal
'...'Character literal
b'...'ASCII byte literal
|…| exprClosure
!Always empty bottom type for diverging functions
_“Ignored” pattern binding; also used to make integer literals readable

表B-3显示了在通过模块层次结构到项的路径中出现的符号。

表 B-3:路径相关语法

SymbolExplanation
ident::identNamespace path
::pathPath relative to the extern prelude, where all other crates are rooted (i.e., an explicitly absolute path including crate name)
self::pathPath relative to the current module (i.e., an explicitly relative path).
super::pathPath relative to the parent of the current module
type::ident, <type as trait>::identAssociated constants, functions, and types
<type>::...Associated item for a type that cannot be directly named (e.g., <&T>::..., <[T]>::..., etc.)
trait::method(...)Disambiguating a method call by naming the trait that defines it
type::method(...)Disambiguating a method call by naming the type for which it’s defined
<type as trait>::method(...)Disambiguating a method call by naming the trait and type

表B-4显示了在使用泛型类型参数的上下文中出现的符号。

表 B-4:泛型

SymbolExplanation
path<...>Specifies parameters to generic type in a type (e.g., Vec<u8>)
path::<...>, method::<...>Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., "42".parse::<i32>())
fn ident<...> ...Define generic function
struct ident<...> ...Define generic structure
enum ident<...> ...Define generic enumeration
impl<...> ...Define generic implementation
for<...> typeHigher-ranked lifetime bounds
type<ident=type>A generic type where one or more associated types have specific assignments (e.g., Iterator<Item=T>)

表B-5显示了在使用特征边界限制泛型类型参数时出现的符号。

表 B-5:特征边界约束

SymbolExplanation
T: UGeneric parameter T constrained to types that implement U
T: 'aGeneric type T must outlive lifetime 'a (meaning the type cannot transitively contain any references with lifetimes shorter than 'a)
T: 'staticGeneric type T contains no borrowed references other than 'static ones
'b: 'aGeneric lifetime 'b must outlive lifetime 'a
T: ?SizedAllow generic type parameter to be a dynamically sized type
'a + trait, trait + traitCompound type constraint

表B-6显示了在调用或定义宏以及在项上指定属性时出现的符号。

表 B-6:宏和属性

SymbolExplanation
#[meta]Outer attribute
#![meta]Inner attribute
$identMacro substitution
$ident:kindMacro capture
$(…)…Macro repetition
ident!(...), ident!{...}, ident![...]Macro invocation

表 B-7 显示了创建注释的符号。

表 B-7:注释

SymbolExplanation
//Line comment
//!Inner line doc comment
///Outer line doc comment
/*...*/Block comment
/*!...*/Inner block doc comment
/**...*/Outer block doc comment

表 B-8 显示了在使用元组时出现的符号。

表 B-8:元组

SymbolExplanation
()Empty tuple (aka unit), both literal and type
(expr)Parenthesized expression
(expr,)Single-element tuple expression
(type,)Single-element tuple type
(expr, ...)Tuple expression
(type, ...)Tuple type
expr(expr, ...)Function call expression; also used to initialize tuple structs and tuple enum variants
expr.0, expr.1, etc.Tuple indexing

表 B-9 显示了使用大括号的上下文。

表 B-9:大括号

ContextExplanation
{...}Block expression
Type {...}struct literal

表 B-10 显示了方括号使用的上下文。

表 B-10:方括号

ContextExplanation
[...]Array literal
[expr; len]Array literal containing len copies of expr
[type; len]Array type containing len instances of type
expr[expr]Collection indexing. Overloadable (Index, IndexMut)
expr[..], expr[a..], expr[..b], expr[a..b]Collection indexing pretending to be collection slicing, using Range, RangeFrom, RangeTo, or RangeFull as the “index”