返回首页返回书籍《The Rust Programming Language》
目录

目录 · CONTENTS

  1. 01The Rust Programming Language
  2. 02Foreword
  3. 03Introduction
  4. 04Getting Started
  5. 05Installation
  6. 06Hello, World!
  7. 07Hello, Cargo!
  8. 08Programming a Guessing Game
  9. 09Common Programming Concepts
  10. 10Variables and Mutability
  11. 11Data Types
  12. 12Functions
  13. 13Comments
  14. 14Control Flow
  15. 15Understanding Ownership
  16. 16What is Ownership?
  17. 17References and Borrowing
  18. 18The Slice Type
  19. 19Using Structs to Structure Related Data
  20. 20Defining and Instantiating Structs
  21. 21An Example Program Using Structs
  22. 22Methods
  23. 23Enums and Pattern Matching
  24. 24Defining an Enum
  25. 25The `match` Control Flow Construct
  26. 26Concise Control Flow with `if let` and `let...else`
  27. 27Packages, Crates, and Modules
  28. 28Packages and Crates
  29. 29Control Scope and Privacy with Modules
  30. 30Paths for Referring to an Item in the Module Tree
  31. 31Bringing Paths Into Scope with the `use` Keyword
  32. 32Separating Modules into Different Files
  33. 33Common Collections
  34. 34Storing Lists of Values with Vectors
  35. 35Storing UTF-8 Encoded Text with Strings
  36. 36Storing Keys with Associated Values in Hash Maps
  37. 37Error Handling
  38. 38Unrecoverable Errors with `panic!`
  39. 39Recoverable Errors with `Result`
  40. 40To `panic!` or Not to `panic!`
  41. 41Generic Types, Traits, and Lifetimes
  42. 42Generic Data Types
  43. 43Defining Shared Behavior with Traits
  44. 44Validating References with Lifetimes
  45. 45Writing Automated Tests
  46. 46How to Write Tests
  47. 47Controlling How Tests Are Run
  48. 48Test Organization
  49. 49An I/O Project: Building a Command Line Program
  50. 50Accepting Command Line Arguments
  51. 51Reading a File
  52. 52Refactoring to Improve Modularity and Error Handling
  53. 53Adding Functionality with Test Driven Development
  54. 54Working with Environment Variables
  55. 55Redirecting Errors to Standard Error
  56. 56Functional Language Features: Iterators and Closures
  57. 57Closures
  58. 58Processing a Series of Items with Iterators
  59. 59Improving Our I/O Project
  60. 60Performance in Loops vs. Iterators
  61. 61More About Cargo and Crates.io
  62. 62Customizing Builds with Release Profiles
  63. 63Publishing a Crate to Crates.io
  64. 64Cargo Workspaces
  65. 65Installing Binaries with `cargo install`
  66. 66Extending Cargo with Custom Commands
  67. 67Smart Pointers
  68. 68Using `Box<T>` to Point to Data on the Heap
  69. 69Treating Smart Pointers Like Regular References
  70. 70Running Code on Cleanup with the `Drop` Trait
  71. 71`Rc<T>`, the Reference Counted Smart Pointer
  72. 72`RefCell<T>` and the Interior Mutability Pattern
  73. 73Reference Cycles Can Leak Memory
  74. 74Fearless Concurrency
  75. 75Using Threads to Run Code Simultaneously
  76. 76Transfer Data Between Threads with Message Passing
  77. 77Shared-State Concurrency
  78. 78Extensible Concurrency with `Send` and `Sync`
  79. 79Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams
  80. 80extern crate trpl; // required for mdbook test
  81. 81Applying Concurrency with Async
  82. 82Working With Any Number of Futures
  83. 83Streams: Futures in Sequence
  84. 84A Closer Look at the Traits for Async
  85. 85Futures, Tasks, and Threads
  86. 86Object-Oriented Programming Features
  87. 87Characteristics of Object-Oriented Languages
  88. 88Using Trait Objects to Abstract over Shared Behavior
  89. 89Implementing an Object-Oriented Design Pattern
  90. 90Patterns and Matching
  91. 91All the Places Patterns Can Be Used
  92. 92Refutability: Whether a Pattern Might Fail to Match
  93. 93Pattern Syntax
  94. 94Advanced Features
  95. 95Unsafe Rust
  96. 96Advanced Traits
  97. 97Advanced Types
  98. 98Advanced Functions and Closures
  99. 99Macros
  100. 100Final Project: Building a Multithreaded Web Server
  101. 101Building a Single-Threaded Web Server
  102. 102From Single-Threaded to Multithreaded Server
  103. 103Graceful Shutdown and Cleanup
  104. 104Appendix
  105. 105A - Keywords
  106. 106B - Operators and Symbols
  107. 107C - Derivable Traits
  108. 108D - Useful Development Tools
  109. 109E - Editions
  110. 110F - Translations of the Book
  111. 111G - How Rust is Made and “Nightly Rust”
第 106 / 111 节

第 106 节 · SECTION 106

B - Operators and Symbols

Appendix B: Operators and Symbols

This appendix contains a glossary of Rust’s syntax, including operators and other symbols that appear by themselves or in the context of paths, generics, trait bounds, macros, attributes, comments, tuples, and brackets.

Operators

Table B-1 contains the operators in Rust, an example of how the operator would appear in context, a short explanation, and whether that operator is overloadable. If an operator is overloadable, the relevant trait to use to overload that operator is listed.

Table B-1: Operators

Operator Example Explanation Overloadable?
! ident!(...), ident!{...}, ident![...] Macro expansion
! !expr Bitwise or logical complement Not
!= expr != expr Nonequality comparison PartialEq
% expr % expr Arithmetic remainder Rem
%= var %= expr Arithmetic remainder and assignment RemAssign
& &expr, &mut expr Borrow
& &type, &mut type, &'a type, &'a mut type Borrowed pointer type
& expr & expr Bitwise AND BitAnd
&= var &= expr Bitwise AND and assignment BitAndAssign
&& expr && expr Short-circuiting logical AND
* expr * expr Arithmetic multiplication Mul
*= var *= expr Arithmetic multiplication and assignment MulAssign
* *expr Dereference Deref
* *const type, *mut type Raw pointer
+ trait + trait, 'a + trait Compound type constraint
+ expr + expr Arithmetic addition Add
+= var += expr Arithmetic addition and assignment AddAssign
, expr, expr Argument and element separator
- - expr Arithmetic negation Neg
- expr - expr Arithmetic subtraction Sub
-= var -= expr Arithmetic subtraction and assignment SubAssign
-> fn(...) -> type, |...| -> type Function and closure return type
. expr.ident Field access
. expr.ident(expr, ...) Method call
. expr.0, expr.1, and so on Tuple indexing
.. .., expr.., ..expr, expr..expr Right-exclusive range literal PartialOrd
..= ..=expr, expr..=expr Right-inclusive range literal PartialOrd
.. ..expr Struct 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 / expr Arithmetic division Div
/= var /= expr Arithmetic division and assignment DivAssign
: pat: type, ident: type Constraints
: ident: expr Struct field initializer
: 'a: loop {...} Loop label
; expr; Statement and item terminator
; [...; len] Part of fixed-size array syntax
<< expr << expr Left-shift Shl
<<= var <<= expr Left-shift and assignment ShlAssign
< expr < expr Less than comparison PartialOrd
<= expr <= expr Less than or equal to comparison PartialOrd
= var = expr, ident = type Assignment/equivalence
== expr == expr Equality comparison PartialEq
=> pat => expr Part of match arm syntax
> expr > expr Greater than comparison PartialOrd
>= expr >= expr Greater than or equal to comparison PartialOrd
>> expr >> expr Right-shift Shr
>>= var >>= expr Right-shift and assignment ShrAssign
@ ident @ pat Pattern binding
^ expr ^ expr Bitwise exclusive OR BitXor
^= var ^= expr Bitwise exclusive OR and assignment BitXorAssign
| pat | pat Pattern alternatives
| expr | expr Bitwise OR BitOr
|= var |= expr Bitwise OR and assignment BitOrAssign
|| expr || expr Short-circuiting logical OR
? expr? Error propagation

Non-operator Symbols

The following tables contain all symbols that don’t function as operators; that is, they don’t behave like a function or method call.

Table B-2 shows symbols that appear on their own and are valid in a variety of locations.

Table B-2: Stand-alone Syntax

Symbol Explanation
'ident Named lifetime or loop label
Digits immediately followed by u8, i32, f64, usize, and so on Numeric literal of specific type
"..." String literal
r"...", r#"..."#, r##"..."##, and so on Raw string literal; escape characters not processed
b"..." Byte string literal; constructs an array of bytes instead of a string
br"...", br#"..."#, br##"..."##, and so on Raw byte string literal; combination of raw and byte string literal
'...' Character literal
b'...' ASCII byte literal
|...| expr Closure
! Always-empty bottom type for diverging functions
_ “Ignored” pattern binding; also used to make integer literals readable

Table B-3 shows symbols that appear in the context of a path through the module hierarchy to an item.

Table B-3: Path-Related Syntax

Symbol Explanation
ident::ident Namespace path
::path Path relative to the crate root (that is, an explicitly absolute path)
self::path Path relative to the current module (that is, an explicitly relative path)
super::path Path relative to the parent of the current module
type::ident, <type as trait>::ident Associated constants, functions, and types
<type>::... Associated item for a type that cannot be directly named (for example, <&T>::..., <[T]>::..., and so on)
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

Table B-4 shows symbols that appear in the context of using generic type parameters.

Table B-4: Generics

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

Table B-5 shows symbols that appear in the context of constraining generic type parameters with trait bounds.

Table B-5: Trait Bound Constraints

Symbol Explanation
T: U Generic parameter T constrained to types that implement U
T: 'a Generic type T must outlive lifetime 'a (meaning the type cannot transitively contain any references with lifetimes shorter than 'a)
T: 'static Generic type T contains no borrowed references other than 'static ones
'b: 'a Generic lifetime 'b must outlive lifetime 'a
T: ?Sized Allow generic type parameter to be a dynamically sized type
'a + trait, trait + trait Compound type constraint

Table B-6 shows symbols that appear in the context of calling or defining macros and specifying attributes on an item.

Table B-6: Macros and Attributes

Symbol Explanation
#[meta] Outer attribute
#![meta] Inner attribute
$ident Macro substitution
$ident:kind Macro metavariable
$(...)... Macro repetition
ident!(...), ident!{...}, ident![...] Macro invocation

Table B-7 shows symbols that create comments.

Table B-7: Comments

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

Table B-8 shows the contexts in which parentheses are used.

Table B-8: Parentheses

Symbol Explanation
() 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

Table B-9 shows the contexts in which curly brackets are used.

Table B-9: Curly Brackets

Context Explanation
{...} Block expression
Type {...} Struct literal

Table B-10 shows the contexts in which square brackets are used.

Table B-10: Square Brackets

Context Explanation
[...] 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”