运算符表达式
Syntax
OperatorExpression →
BorrowExpression
| DereferenceExpression
| TryPropagationExpression
| NegationExpression
| ArithmeticOrLogicalExpression
| ComparisonExpression
| LazyBooleanExpression
| TypeCastExpression
| AssignmentExpression
| CompoundAssignmentExpression
运算符由 Rust 语言为内置类型定义。
以下许多运算符也可以使用 std::ops 或 std::cmp 中的 trait 进行重载。
溢出
在调试模式下编译时,整数运算符在溢出时会 panic。-C debug-assertions 和 -C overflow-checks 编译器标志可用于更直接地控制此行为。以下情况被视为溢出:
- 当
+、*或二元-创建的值大于最大值或小于可存储的最小值时。
- 使用
/或%,其中左参数是有符号整数类型的最小整数,右参数是-1。出于遗留原因,即使禁用了-C overflow-checks,也会发生这些检查。
- 使用
<<或>>,其中右参数大于或等于左参数类型中的位数,或者是负数。
Note
一元
-后面的字面量表达式的例外意味着-128_i8或let j: i8 = -(128)等形式永远不会导致 panic,并且具有预期值 -128。在这些情况下,字面量表达式已经具有其类型的最负值(例如,
128_i8的值为 -128),因为整数字面量按整数字面量表达式中的描述截断为其类型。由于二进制补码溢出约定,对这些最负值的取反使值保持不变。
在
rustc中,这些最负表达式也被overflowing_literalslint 检查忽略。
借用运算符
Syntax
BorrowExpression →
( & | && ) Expression
| ( & | && ) mut Expression
| ( & | && ) raw const Expression
| ( & | && ) raw mut Expression
&(共享借用)和 &mut(可变借用)运算符是一元前缀运算符。
当应用于位置表达式时,此表达式产生指向值所引用位置的引用(指针)。
在引用期间,内存位置也被置于借用状态。对于共享借用(&),这意味着该位置不能被修改,但可以被读取或再次共享。对于可变借用(&mut),在借用到期之前不能以任何方式访问该位置。
&mut 在可变位置表达式上下文中求值其操作数。
如果 & 或 &mut 运算符应用于值表达式,则会创建临时值。
这些运算符不能被重载。
#![allow(unused)]
fn main() {
{
// a temporary with value 7 is created that lasts for this scope.
let shared_reference = &7;
}
let mut array = [-2, 3, 9];
{
// Mutably borrows `array` for this scope.
// `array` may only be used through `mutable_reference`.
let mutable_reference = &mut array;
}
}
即使 && 是单个词法单元(惰性 ‘and’ 运算符),当在借用表达式上下文中使用时,它作为两个借用工作:
#![allow(unused)]
fn main() {
// same meanings:
let a = && 10;
let a = & & 10;
// same meanings:
let a = &&&& mut 10;
let a = && && mut 10;
let a = & & & & mut 10;
}
原始借用运算符
&raw const 和 &raw mut 是原始借用运算符。
这些运算符的操作数表达式在位置表达式上下文中求值。
&raw const expr 然后创建指向给定位置的类型为 *const T 的 const 原始指针,&raw mut expr 创建类型为 *mut T 的可变原始指针。
当位置表达式可能求值为未正确对齐或未存储由其类型确定的有效值的位置时,或者当创建引用会引入不正确的别名假设时,必须使用原始借用运算符而不是借用运算符。在这些情况下,使用借用运算符会通过创建无效引用导致未定义行为,但仍然可以构造原始指针。
以下是通过 packed 结构体创建指向未对齐位置的原始指针的示例:
#![allow(unused)]
fn main() {
#[repr(packed)]
struct Packed {
f1: u8,
f2: u16,
}
let packed = Packed { f1: 1, f2: 2 };
// `&packed.f2` would create an unaligned reference, and thus be undefined behavior!
let raw_f2 = &raw const packed.f2;
assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
}
以下是创建指向不包含有效值的位置的原始指针的示例:
#![allow(unused)]
fn main() {
use std::mem::MaybeUninit;
struct Demo {
field: bool,
}
let mut uninit = MaybeUninit::<Demo>::uninit();
// `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
// and thus be undefined behavior!
let f1_ptr = unsafe { &raw mut (*uninit.as_mut_ptr()).field };
unsafe { f1_ptr.write(true); }
let init = unsafe { uninit.assume_init() };
}
解引用运算符
Syntax
DereferenceExpression → * Expression
*(解引用)运算符也是一元前缀运算符。
如果表达式类型为 &mut T、*mut T 或 Box<T>,并且是局部变量、局部变量的(嵌套)字段或可变位置表达式,则可以对结果内存位置进行赋值。
解引用原始指针需要 unsafe。
在非指针类型上,*x 在不可变位置表达式上下文中等同于 *std::ops::Deref::deref(&x),在可变位置表达式上下文中等同于 *std::ops::DerefMut::deref_mut(&mut x),但当 *x 经历临时生命周期扩展时,解引用的表达式 x 的临时作用域也会被扩展。
#![allow(unused)]
fn main() {
struct NoCopy;
let a = &7;
assert_eq!(*a, 7);
let b = &mut 9;
*b = 11;
assert_eq!(*b, 11);
let c = Box::new(NoCopy);
let d: NoCopy = *c;
}
#![allow(unused)]
fn main() {
// The temporary holding the result of `String::new()` is extended
// to live to the end of the block, so `x` may be used in subsequent
// statements.
let x = &*String::new();
x;
}
#![allow(unused)]
fn main() {
// The temporary holding the result of `String::new()` is dropped at
// the end of the statement, so it's an error to use `y` after.
let y = &*std::ops::Deref::deref(&String::new()); // ERROR
y;
}
Try 传播表达式
Syntax
TryPropagationExpression → Expression ?
Try 传播表达式使用内部表达式的值和 Try trait 来决定是产生值(如果是,产生什么值)还是返回值给调用者(如果是,返回什么值)。
Example
#![allow(unused)] fn main() { use std::num::ParseIntError; fn try_to_parse() -> Result<i32, ParseIntError> { let x: i32 = "123".parse()?; // `x` is `123`. let y: i32 = "24a".parse()?; // Returns an `Err()` immediately. Ok(x + y) // Doesn't run. } let res = try_to_parse(); println!("{res:?}"); assert!(res.is_err()) }#![allow(unused)] fn main() { fn try_option_some() -> Option<u8> { let val = Some(1)?; Some(val) } assert_eq!(try_option_some(), Some(1)); fn try_option_none() -> Option<u8> { let val = None?; Some(val) } assert_eq!(try_option_none(), None); }use std::ops::ControlFlow; pub struct TreeNode<T> { value: T, left: Option<Box<TreeNode<T>>>, right: Option<Box<TreeNode<T>>>, } impl<T> TreeNode<T> { pub fn traverse_inorder<B>(&self, f: &mut impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> { if let Some(left) = &self.left { left.traverse_inorder(f)?; } f(&self.value)?; if let Some(right) = &self.right { right.traverse_inorder(f)?; } ControlFlow::Continue(()) } } fn main() { let n = TreeNode { value: 1, left: Some(Box::new(TreeNode{value: 2, left: None, right: None})), right: None, }; let v = n.traverse_inorder(&mut |t| { if *t == 2 { ControlFlow::Break("found") } else { ControlFlow::Continue(()) } }); assert_eq!(v, ControlFlow::Break("found")); }
Note
Trytrait 目前不稳定,因此不能为用户类型实现。Try 传播表达式目前大致等同于:
#![allow(unused)] fn main() { #![ feature(try_trait_v2) ] fn example() -> Result<(), ()> { let expr = Ok(()); match core::ops::Try::branch(expr) { core::ops::ControlFlow::Continue(val) => val, core::ops::ControlFlow::Break(residual) => return core::ops::FromResidual::from_residual(residual), } Ok(()) } }
Note
Try 传播运算符有时称为问号运算符、
?运算符或 try 运算符。
Try 传播运算符可应用于以下类型的表达式:
Result<T, E>Result::Ok(val)求值为val。Result::Err(e)返回Result::Err(From::from(e))。
Option<T>Option::Some(val)求值为val。Option::None返回Option::None。
ControlFlow<B, C>ControlFlow::Continue(c)求值为c。ControlFlow::Break(b)返回ControlFlow::Break(b)。
Poll<Result<T, E>>Poll::Ready(Ok(val))求值为Poll::Ready(val)。Poll::Ready(Err(e))返回Poll::Ready(Err(From::from(e)))。Poll::Pending求值为Poll::Pending。
Poll<Option<Result<T, E>>>Poll::Ready(Some(Ok(val)))求值为Poll::Ready(Some(val))。Poll::Ready(Some(Err(e)))返回Poll::Ready(Some(Err(From::from(e))))。Poll::Ready(None)求值为Poll::Ready(None)。Poll::Pending求值为Poll::Pending。
取反运算符
Syntax
NegationExpression →
- Expression
| ! Expression
这是最后两个一元运算符。
此表总结了它们在原始类型上的行为以及用于为其他类型重载这些运算符的 trait。请记住,有符号整数始终使用二进制补码表示。所有这些运算符的操作数都在值表达式上下文中求值,因此被移动或复制。
| 符号 | 整数 | bool | 浮点数 | 重载 Trait |
|---|---|---|---|---|
- | 取反* | 取反 | std::ops::Neg | |
! | 按位 NOT | 逻辑 NOT | std::ops::Not |
* 仅适用于有符号整数类型。
以下是这些运算符的一些示例
#![allow(unused)]
fn main() {
let x = 6;
assert_eq!(-x, -6);
assert_eq!(!x, -7);
assert_eq!(true, !false);
}
算术和逻辑二元运算符
Syntax
ArithmeticOrLogicalExpression →
Expression + Expression
| Expression - Expression
| Expression * Expression
| Expression / Expression
| Expression % Expression
| Expression & Expression
| Expression | Expression
| Expression ^ Expression
| Expression << Expression
| Expression >> Expression
二元运算符表达式都使用中缀表示法编写。
此表总结了算术和逻辑二元运算符在原始类型上的行为以及用于为其他类型重载这些运算符的 trait。请记住,有符号整数始终使用二进制补码表示。所有这些运算符的操作数都在值表达式上下文中求值,因此被移动或复制。
| 符号 | 整数 | bool | 浮点数 | 重载 Trait | 重载复合赋值 Trait |
|---|---|---|---|---|---|
+ | 加法 | 加法 | std::ops::Add | std::ops::AddAssign | |
- | 减法 | 减法 | std::ops::Sub | std::ops::SubAssign | |
* | 乘法 | 乘法 | std::ops::Mul | std::ops::MulAssign | |
/ | 除法*† | 除法 | std::ops::Div | std::ops::DivAssign | |
% | 取余**† | 取余 | std::ops::Rem | std::ops::RemAssign | |
& | 按位 AND | 逻辑 AND | std::ops::BitAnd | std::ops::BitAndAssign | |
| | 按位 OR | 逻辑 OR | std::ops::BitOr | std::ops::BitOrAssign | |
^ | 按位 XOR | 逻辑 XOR | std::ops::BitXor | std::ops::BitXorAssign | |
<< | 左移 | std::ops::Shl | std::ops::ShlAssign | ||
>> | 右移*** | std::ops::Shr | std::ops::ShrAssign |
* 整数除法向零舍入。
** Rust 使用截断除法定义的取余。给定 remainder = dividend % divisor,余数将与被除数具有相同的符号。
*** 有符号整数类型上的算术右移,无符号整数类型上的逻辑右移。
† 对于整数类型,除以零会 panic。
以下是使用这些运算符的示例。
#![allow(unused)]
fn main() {
assert_eq!(3 + 6, 9);
assert_eq!(5.5 - 1.25, 4.25);
assert_eq!(-5 * 14, -70);
assert_eq!(14 / 3, 4);
assert_eq!(100 % 7, 2);
assert_eq!(0b1010 & 0b1100, 0b1000);
assert_eq!(0b1010 | 0b1100, 0b1110);
assert_eq!(0b1010 ^ 0b1100, 0b110);
assert_eq!(13 << 3, 104);
assert_eq!(-10 >> 2, -3);
}
比较运算符
Syntax
ComparisonExpression →
Expression == Expression
| Expression != Expression
| Expression > Expression
| Expression < Expression
| Expression >= Expression
| Expression <= Expression
比较运算符也为原始类型和标准库中的许多类型定义。
链接比较运算符时需要括号。例如,表达式 a == b == c 无效,可以写成 (a == b) == c。
与算术和逻辑运算符不同,用于重载这些运算符的 trait 更普遍地用于显示如何比较类型,并且可能被使用这些 trait 作为约束的函数假定为定义实际比较。标准库中的许多函数和宏可以使用该假设(尽管不是为了确保安全性)。
与上面的算术和逻辑运算符不同,这些运算符隐式地对其操作数进行共享借用,在位置表达式上下文中求值它们:
#![allow(unused)]
fn main() {
let a = 1;
let b = 1;
a == b;
// is equivalent to
::std::cmp::PartialEq::eq(&a, &b);
}
这意味着不必移出操作数。
| 符号 | 含义 | 重载方法 |
|---|---|---|
== | 等于 | std::cmp::PartialEq::eq |
!= | 不等于 | std::cmp::PartialEq::ne |
> | 大于 | std::cmp::PartialOrd::gt |
< | 小于 | std::cmp::PartialOrd::lt |
>= | 大于或等于 | std::cmp::PartialOrd::ge |
<= | 小于或等于 | std::cmp::PartialOrd::le |
以下是使用比较运算符的示例。
#![allow(unused)]
fn main() {
assert!(123 == 123);
assert!(23 != -12);
assert!(12.5 > 12.2);
assert!([1, 2, 3] < [1, 3, 4]);
assert!('A' <= 'B');
assert!("World" >= "Hello");
}
惰性布尔运算符
Syntax
LazyBooleanExpression →
Expression || Expression
| Expression && Expression
运算符 || 和 && 可以应用于布尔类型的操作数。|| 运算符表示逻辑“或“,&& 运算符表示逻辑“与“。
它们与 | 和 & 的不同之处在于,只有当左操作数尚未确定表达式的结果时,才会求值右操作数。也就是说,|| 仅在左操作数求值为 false 时才求值其右操作数,&& 仅在求值为 true 时才求值。
#![allow(unused)]
fn main() {
let x = false || true; // true
let y = false && panic!(); // false, doesn't evaluate `panic!()`
}
类型转换表达式
Syntax
TypeCastExpression → Expression as TypeNoBounds
类型转换表达式用二元运算符 as 表示。
执行 as 表达式将左侧的值转换为右侧的类型。
as 表达式的示例:
#![allow(unused)]
fn main() {
fn sum(values: &[f64]) -> f64 { 0.0 }
fn len(values: &[f64]) -> i32 { 0 }
fn average(values: &[f64]) -> f64 {
let sum: f64 = sum(values);
let size: f64 = len(values) as f64;
sum / size
}
}
as 可用于显式执行强制转换,以及以下附加转换。任何不符合强制转换规则或表中条目的转换都是编译器错误。这里 *T 表示 *const T 或 *mut T。m 表示引用类型中的可选 mut 和指针类型中的 mut 或 const。
e 的类型 | U | e as U 执行的转换 |
|---|---|---|
| 整数或浮点类型 | 整数或浮点类型 | 数值转换 |
| 枚举 | 整数类型 | 枚举转换 |
bool 或 char | 整数类型 | 原始到整数转换 |
u8 | char | u8 到 char 转换 |
*T | *V(当兼容时) | 指针到指针转换 |
*T(其中 T: Sized) | 整数类型 | 指针到地址转换 |
| 整数类型 | *V(其中 V: Sized) | 地址到指针转换 |
&m₁ [T; n] | *m₂ T 1 | 数组到指针转换 |
*m₁ [T; n] | *m₂ T 1 | 数组到指针转换 |
| 函数项 | 函数指针 | 函数项到函数指针转换 |
| 函数项 | *V(其中 V: Sized) | 函数项到指针转换 |
| 函数项 | 整数 | 函数项到地址转换 |
| 函数指针 | *V(其中 V: Sized) | 函数指针到指针转换 |
| 函数指针 | 整数 | 函数指针到地址转换 |
| 闭包 2 | 函数指针 | 闭包到函数指针转换 |
语义
数值转换
-
在相同大小的两个整数之间转换(例如 i32 -> u32)是无操作(Rust 对固定整数的负值使用 2 的补码)
#![allow(unused)] fn main() { assert_eq!(42i8 as u8, 42u8); assert_eq!(-1i8 as u8, 255u8); assert_eq!(255u8 as i8, -1i8); assert_eq!(-1i16 as u16, 65535u16); }
-
从较大整数转换为较小整数(例如 u32 -> u8)将截断
#![allow(unused)] fn main() { assert_eq!(42u16 as u8, 42u8); assert_eq!(1234u16 as u8, 210u8); assert_eq!(0xabcdu16 as u8, 0xcdu8); assert_eq!(-42i16 as i8, -42i8); assert_eq!(1234u16 as i8, -46i8); assert_eq!(0xabcdi32 as i8, -51i8); }
-
从较小整数转换为较大整数(例如 u8 -> u32)将
- 如果源是无符号的,则零扩展
- 如果源是有符号的,则符号扩展
#![allow(unused)] fn main() { assert_eq!(42i8 as i16, 42i16); assert_eq!(-17i8 as i16, -17i16); assert_eq!(0b1000_1010u8 as u16, 0b0000_0000_1000_1010u16, "Zero-extend"); assert_eq!(0b0000_1010i8 as i16, 0b0000_0000_0000_1010i16, "Sign-extend 0"); assert_eq!(0b1000_1010u8 as i8 as i16, 0b1111_1111_1000_1010u16 as i16, "Sign-extend 1"); }
-
从浮点数转换为整数将向零舍入浮点数
NaN将返回0- 大于最大整数值的值(包括
INFINITY)将饱和到整数类型的最大值。 - 小于最小整数值的值(包括
NEG_INFINITY)将饱和到整数类型的最小值。
#![allow(unused)] fn main() { assert_eq!(42.9f32 as i32, 42); assert_eq!(-42.9f32 as i32, -42); assert_eq!(42_000_000f32 as i32, 42_000_000); assert_eq!(std::f32::NAN as i32, 0); assert_eq!(1_000_000_000_000_000f32 as i32, 0x7fffffffi32); assert_eq!(std::f32::NEG_INFINITY as i32, -0x80000000i32); }
-
从整数转换为浮点数将产生最接近的可能浮点数 *
- 如果需要,舍入根据
roundTiesToEven模式进行 *** - 溢出时,产生无穷大(与输入相同的符号)
- 注意:使用当前的数值类型集,溢出只能在
u128 as f32对于大于或等于f32::MAX + (0.5 ULP)的值时发生
#![allow(unused)] fn main() { assert_eq!(1337i32 as f32, 1337f32); assert_eq!(123_456_789i32 as f32, 123_456_790f32, "Rounded"); assert_eq!(0xffffffff_ffffffff_ffffffff_ffffffff_u128 as f32, std::f32::INFINITY); } - 如果需要,舍入根据
-
从 f32 转换为 f64 是完美且无损的
#![allow(unused)] fn main() { assert_eq!(1_234.5f32 as f64, 1_234.5f64); assert_eq!(std::f32::INFINITY as f64, std::f64::INFINITY); assert!((std::f32::NAN as f64).is_nan()); }
-
从 f64 转换为 f32 将产生最接近的可能 f32 **
- 如果需要,舍入根据
roundTiesToEven模式进行 *** - 溢出时,产生无穷大(与输入相同的符号)
#![allow(unused)] fn main() { assert_eq!(1_234.5f64 as f32, 1_234.5f32); assert_eq!(1_234_567_891.123f64 as f32, 1_234_567_890f32, "Rounded"); assert_eq!(std::f64::INFINITY as f32, std::f32::INFINITY); assert!((std::f64::NAN as f32).is_nan()); } - 如果需要,舍入根据
* 如果硬件不原生支持具有此舍入模式和溢出行为的整数到浮点转换,这些转换可能会比预期慢。
** 如果硬件不原生支持具有此舍入模式和溢出行为的 f64 到 f32 转换,这些转换可能会比预期慢。
*** 如 IEEE 754-2008 §4.3.1 中定义:选择最接近的浮点数,如果恰好在两个浮点数之间,则优先选择最低有效位为偶数的那个。
枚举转换
将枚举转换为其判别值,然后在需要时使用数值转换。转换仅限于以下类型的枚举:
#![allow(unused)]
fn main() {
enum Enum { A, B, C }
assert_eq!(Enum::A as i32, 0);
assert_eq!(Enum::B as i32, 1);
assert_eq!(Enum::C as i32, 2);
}
如果枚举实现 Drop,则不允许转换。
原始到整数转换
false转换为0,true转换为1char转换为代码点的值,然后在需要时使用数值转换。
#![allow(unused)]
fn main() {
assert_eq!(false as i32, 0);
assert_eq!(true as i32, 1);
assert_eq!('A' as i32, 65);
assert_eq!('Ö' as i32, 214);
}
u8 到 char 转换
转换为具有相应代码点的 char。
#![allow(unused)]
fn main() {
assert_eq!(65u8 as char, 'A');
assert_eq!(214u8 as char, 'Ö');
}
指针到地址转换
从原始指针转换为整数会产生引用内存的机器地址。如果整数类型小于指针类型,地址可能会被截断;使用 usize 可以避免这种情况。
地址到指针转换
从整数转换为原始指针将整数解释为内存地址,并产生引用该内存的指针。
Warning
这与仍在开发中的 Rust 内存模型交互。 从此转换获得的指针即使在位级等于有效指针也可能受到额外限制。 如果不遵循别名规则,解引用此类指针可能是未定义行为。
健全地址算术的简单示例:
#![allow(unused)]
fn main() {
let mut values: [i32; 2] = [1, 2];
let p1: *mut i32 = values.as_mut_ptr();
let first_address = p1 as usize;
let second_address = first_address + 4; // 4 == size_of::<i32>()
let p2 = second_address as *mut i32;
unsafe {
*p2 += 1;
}
assert_eq!(values[1], 3);
}
指针到指针转换
*const T / *mut T 可以转换为 *const U / *mut U,具有以下行为:
-
如果
T和U都是有大小的,则指针不变返回。Example
#![allow(unused)] fn main() { let x: i32 = 42; let p1: *const i32 = &x; let p2: *const u8 = p1 as *const u8; // The pointer address remains the same. assert_eq!(p1 as usize, p2 as usize); }
-
如果
T是未大小的,U是有大小的,则转换丢弃完成宽指针T的所有元数据,并产生由未大小指针的数据部分组成的窄指针U。Example
#![allow(unused)] fn main() { let slice: &[i32] = &[1, 2, 3]; let ptr: *const [i32] = slice as *const [i32]; // Cast from wide pointer (*const [i32]) to thin pointer (*const i32) // discarding the length metadata. let data_ptr: *const i32 = ptr as *const i32; assert_eq!(unsafe { *data_ptr }, 1); }
- 如果
T和U都是未大小的,则指针也不变返回。特别是,元数据被精确保留。只有当元数据根据以下规则兼容时,才能执行转换:
-
当
T和U是具有切片元数据的未大小类型时,它们始终兼容。切片的元数据是元素数量,因此将*[u16] -> *[u8]转换是合法的,但会导致字节数减半。Example
#![allow(unused)] fn main() { let slice: &[u16] = &[1, 2, 3]; let ptr: *const [u16] = slice as *const [u16]; let byte_ptr: *const [u8] = ptr as *const [u8]; assert_eq!(byte_ptr.len(), 3); }
- 当
T和U是具有 trait 对象元数据的未大小类型时,元数据仅在以下所有条件成立时才兼容:-
主要 trait 必须相同。
Example
#![allow(unused)] fn main() { trait Foo {} trait Bar {} impl Foo for i32 {} impl Bar for i32 {} let x: i32 = 42; let ptr_foo: *const dyn Foo = &x as *const dyn Foo; // You can't cast to a different principal trait. let ptr_bar: *const dyn Bar = ptr_foo as *const dyn Bar; // ERROR } -
可以移除自动 trait。
Example
#![allow(unused)] fn main() { trait Foo {} struct S; impl Foo for S {} unsafe impl Send for S {} let s = S; let ptr_send: *const (dyn Foo + Send) = &s; // Removing an auto trait. let ptr_no_send: *const dyn Foo = ptr_send as *const dyn Foo; } -
只有当自动 trait 是主要 trait 的超级 trait 时,才能添加自动 trait。
Example
#![allow(unused)] fn main() { trait Foo: Send {} struct S; impl Foo for S {} unsafe impl Send for S {} let s = S; let ptr_no_send: *const dyn Foo = &s; // Adding an auto trait. let ptr_send: *const (dyn Foo + Send) = ptr_no_send as *const (dyn Foo + Send); }#![allow(unused)] fn main() { trait Foo {} struct S; impl Foo for S {} unsafe impl Send for S {} let s = S; let ptr_no_send: *const dyn Foo = &s; // Same as above, except trait Foo does not have Send as a super trait. let ptr_send: *const (dyn Foo + Send) = ptr_no_send as *const (dyn Foo + Send); // ERROR } -
尾部生命周期只能缩短。
Example
#![allow(unused)] fn main() { trait Foo {} fn shorten_lifetime<'long: 'short, 'short>( ptr: *const (dyn Foo + 'long), ) -> *const (dyn Foo + 'short) { // Shortening the lifetime is allowed. ptr as *const (dyn Foo + 'short) } }#![allow(unused)] fn main() { trait Foo {} fn lengthen_lifetime<'long: 'short, 'short>( ptr: *const (dyn Foo + 'short), ) -> *const (dyn Foo + 'long) { // It is not allowed to cast to a longer lifetime. ptr as *const (dyn Foo + 'long) // ERROR } } -
泛型(包括生命周期)和关联类型必须完全匹配。
Example
#![allow(unused)] fn main() { trait Generic<T> {} impl Generic<i32> for () {} impl Generic<u32> for () {} let x = (); let ptr_i32: *const dyn Generic<i32> = &x; // You can't cast to a different generic parameter. let ptr_u32: *const dyn Generic<u32> = ptr_i32 as *const dyn Generic<u32>; // ERROR }#![allow(unused)] fn main() { trait HasType { type Output; } trait Generic<'x, T> {} fn cast_via_associated<'a, 'b, A, B>( ptr: *const dyn Generic<'a, A::Output>, ) -> *const dyn Generic<'b, B::Output> where 'a: 'b, 'b: 'a, A: HasType, B: HasType<Output = A::Output>, // Forces equality { ptr as *const dyn Generic<'b, B::Output> } }
-
-
当
T或U是最后一个字段未大小的结构体或元组类型时,它具有与其最后一个字段相同的元数据和兼容性规则。Example
#![allow(unused)] fn main() { struct Wrapper(u32, [u8]); let slice: &[u8] = &[1, 2, 3]; let ptr: *const [u8] = slice; // The metadata (length 3) is preserved when casting to a struct // where the last field is the unsized type `[u8]`. let wrapper_ptr: *const Wrapper = ptr as *const Wrapper; // And preserved when casting back. let ptr_back: *const [u8] = wrapper_ptr as *const [u8]; assert_eq!(ptr_back.len(), 3); }
赋值表达式
Syntax
AssignmentExpression → Expression = Expression
赋值表达式将值移入指定位置。
赋值表达式由可变的赋值表达式(赋值操作数)后跟等号(=)和值表达式(赋值值操作数)组成。
在其最基本的形式中,赋值表达式是位置表达式,我们首先讨论这种情况。
下面讨论更一般的解构赋值情况,但这种情况总是分解为对位置表达式的顺序赋值,可以认为是更基本的情况。
基本赋值
求值赋值表达式从求值其操作数开始。首先求值赋值值操作数,然后求值赋值表达式。
对于解构赋值,赋值表达式的子表达式从左到右求值。
Note
这与其他表达式不同,因为右操作数在左操作数之前求值。
然后它具有首先丢弃赋值位置的值的效果,除非该位置是未初始化的局部变量或局部变量的未初始化字段。
接下来,它要么复制或移动赋值值到赋值位置。
赋值表达式始终产生单元值。
示例:
#![allow(unused)]
fn main() {
let mut x = 0;
let y = 0;
x = y;
}
解构赋值
解构赋值是变量声明的解构模式匹配的对应物,允许对复杂值(如元组或结构体)进行赋值。例如,我们可以交换两个可变变量:
#![allow(unused)]
fn main() {
let (mut a, mut b) = (0, 1);
// Swap `a` and `b` using destructuring assignment.
(b, a) = (a, b);
}
与使用 let 的解构声明相比,由于语法歧义,模式不能出现在赋值的左侧。相反,一组对应于模式的表达式被指定为赋值表达式,并允许在赋值的左侧。然后赋值表达式被脱糖为模式匹配,然后是顺序赋值。
脱糖的模式必须是不可反驳的:特别是,这意味着只有长度在编译时已知的切片模式和简单切片 [..] 才允许用于解构赋值。
脱糖方法很简单,最好通过示例说明。
#![allow(unused)]
fn main() {
struct Struct { x: u32, y: u32 }
let (mut a, mut b) = (0, 0);
(a, b) = (3, 4);
[a, b] = [3, 4];
Struct { x: a, y: b } = Struct { x: 3, y: 4};
// desugars to:
{
let (_a, _b) = (3, 4);
a = _a;
b = _b;
}
{
let [_a, _b] = [3, 4];
a = _a;
b = _b;
}
{
let Struct { x: _a, y: _b } = Struct { x: 3, y: 4};
a = _a;
b = _b;
}
}
标识符不被禁止在单个赋值表达式中多次使用。
请注意,默认绑定模式不适用于脱糖表达式。
Note
脱糖限制了解构赋值的赋值值操作数(RHS)的临时作用域。
在基本赋值中,临时值在封闭临时作用域的末尾被丢弃。下面是语句。因此,允许赋值和使用。
#![allow(unused)] fn main() { fn temp() {} fn f<T>(x: T) -> T { x } let x; (x = f(&temp()), x); // OK }相反,在解构赋值中,临时值在脱糖的
let语句末尾被丢弃。由于这发生在我们尝试对x赋值之前,下面的代码失败。#![allow(unused)] fn main() { fn temp() {} fn f<T>(x: T) -> T { x } let x; [x] = [f(&temp())]; // ERROR }这脱糖为:
#![allow(unused)] fn main() { fn temp() {} fn f<T>(x: T) -> T { x } let x; { let [_x] = [f(&temp())]; // ^ // The temporary is dropped here. x = _x; // ERROR } }
Note
由于脱糖,解构赋值的赋值值操作数(RHS)是新引入的块中的扩展表达式。
下面,因为临时作用域被扩展到此引入块的末尾,所以允许赋值。
#![allow(unused)] fn main() { fn temp() {} let x; [x] = [&temp()]; // OK }这脱糖为:
#![allow(unused)] fn main() { fn temp() {} let x; { let [_x] = [&temp()]; x = _x; } // OK }然而,如果我们尝试使用
x,即使在同一语句中,我们也会收到错误,因为临时值在此引入块的末尾被丢弃。#![allow(unused)] fn main() { fn temp() {} let x; ([x] = [&temp()], x); // ERROR }这脱糖为:
#![allow(unused)] fn main() { fn temp() {} let x; ( { let [_x] = [&temp()]; x = _x; }, // <-- The temporary is dropped here. x, // ERROR ); }
复合赋值表达式
Syntax
CompoundAssignmentExpression →
Expression += Expression
| Expression -= Expression
| Expression *= Expression
| Expression /= Expression
| Expression %= Expression
| Expression &= Expression
| Expression |= Expression
| Expression ^= Expression
| Expression <<= Expression
| Expression >>= Expression
复合赋值表达式将算术和逻辑二元运算符与赋值表达式结合。
例如:
#![allow(unused)]
fn main() {
let mut x = 5;
x += 1;
assert!(x == 6);
}
复合赋值的语法是可变的位置表达式(赋值操作数),然后是其中一个运算符后跟 = 作为单个词法单元(无空白),然后是值表达式(修改操作数)。
与其他位置操作数不同,赋值位置操作数必须是位置表达式。
尝试使用值表达式是编译器错误,而不是将其提升为临时值。
复合赋值表达式的求值取决于操作数的类型。
如果两个操作数的类型在单态化之前已知为原始类型,则首先求值右侧,然后求值左侧,并通过将运算符应用于两侧的值来修改左侧求值给出的位置。
use core::{num::Wrapping, ops::AddAssign};
trait Equate {}
impl<T> Equate for (T, T) {}
fn f1(x: (u8,)) {
let mut order = vec![];
// The RHS is evaluated first as both operands are of primitive
// type.
{ order.push(2); x }.0 += { order.push(1); x }.0;
assert!(order.is_sorted());
}
fn f2(x: (Wrapping<u8>,)) {
let mut order = vec![];
// The LHS is evaluated first as `Wrapping<_>` is not a primitive
// type.
{ order.push(1); x }.0 += { order.push(2); (0u8,) }.0;
assert!(order.is_sorted());
}
fn f3<T: AddAssign<u8> + Copy>(x: (T,)) where (T, u8): Equate {
let mut order = vec![];
// The LHS is evaluated first as one of the operands is a generic
// parameter, even though that generic parameter can be unified
// with a primitive type due to the where clause bound.
{ order.push(1); x }.0 += { order.push(2); (0u8,) }.0;
assert!(order.is_sorted());
}
fn main() {
f1((0u8,));
f2((Wrapping(0u8),));
// We supply a primitive type as the generic argument, but this
// does not affect the evaluation order in `f3` when
// monomorphized.
f3::<u8>((0u8,));
}
Note
这是不寻常的。其他地方从左到右求值是规范。
有关更多示例,请参阅求值顺序测试。
否则,此表达式是使用运算符对应 trait(参见 expr.arith-logic.behavior)并以其方法作为接收者调用左侧,右侧作为下一个参数的语法糖。
例如,以下两个语句是等效的:
#![allow(unused)]
fn main() {
use std::ops::AddAssign;
fn f<T: AddAssign + Copy>(mut x: T, y: T) {
x += y; // Statement 1.
x.add_assign(y); // Statement 2.
}
}
Note
令人惊讶的是,将其进一步脱糖为完全限定的方法调用并不等效,因为当通过 autoref 获取对第一个操作数的可变引用时,借用检查器有特殊行为。
#![allow(unused)] fn main() { use std::ops::AddAssign; fn f<T: AddAssign + Copy>(mut x: T) { // Here we used `x` as both the LHS and the RHS. Because the // mutable borrow of the LHS needed to call the trait method // is taken implicitly by autoref, this is OK. x += x; //~ OK x.add_assign(x); //~ OK } }#![allow(unused)] fn main() { use std::ops::AddAssign; fn f<T: AddAssign + Copy>(mut x: T) { // We can't desugar the above to the below, as once we take the // mutable borrow of `x` to pass the first argument, we can't // pass `x` by value in the second argument because the mutable // reference is still live. <T as AddAssign>::add_assign(&mut x, x); //~^ ERROR cannot use `x` because it was mutably borrowed } }#![allow(unused)] fn main() { use std::ops::AddAssign; fn f<T: AddAssign + Copy>(mut x: T) { // As above. (&mut x).add_assign(x); //~^ ERROR cannot use `x` because it was mutably borrowed } }
与普通赋值表达式一样,复合赋值表达式始终产生单元值。
Warning
避免编写依赖于复合赋值中操作数求值顺序的代码,因为它可能不寻常且令人惊讶。