对于所有类型的“T”、“U”,如果“T”被强制转换为“U”,那么“&T”是否被强制转换为“&U”?
Is it true that for all types `T`, `U` if `T` is coerced to `U` then `&T` is coerced to `&U`?
是well documented that [T; n]
can coerce to [T]
. The following code is also well-formed:
fn test(){
let _a: &[i32] = &[1, 2, 3];
}
这里我们将 &[T; n]
强制转换为 &[T]
。
是否对于所有类型 T
,U
如果 T
被强制转换为 U
那么 &T
被强制转换为 &U
?
它没有在参考文献中记录(至少明确地)。
不行,因为多加一层&
会导致失败:
fn oops() {
let a: &[i32; 3] = &[1, 2, 3];
let _b: &&[i32] = &a;
}
error[E0308]: mismatched types
--> src/lib.rs:8:23
|
8 | let _b: &&[i32] = &a;
| ------- ^^ expected slice `[i32]`, found array `[i32; 3]`
| |
| expected due to this
|
= note: expected reference `&&[i32]`
found reference `&&[i32; 3]`
此外,[T; n]
与 &[T; n]
强制转换为 [T]
的情况不同强制 &[T]
。您链接的文档描述了与未调整大小的强制转换相关的两个特征:Unsize
和 CoerceUnsized
。 [T; n]
实现了 Unsize<[T]>
,并且 因此 &[T; n]
实现了 CoerceUnsized<&[T]>
;这本质上是同一件事,您的代码有效地展示了两者。如果不使用引用(或某种类型的指针),就不可能编写一个将 [T; n]
强制转换为 [T]
的函数,因为缩小强制只发生在一些后面一种指针。
是well documented that [T; n]
can coerce to [T]
. The following code is also well-formed:
fn test(){
let _a: &[i32] = &[1, 2, 3];
}
这里我们将 &[T; n]
强制转换为 &[T]
。
是否对于所有类型 T
,U
如果 T
被强制转换为 U
那么 &T
被强制转换为 &U
?
它没有在参考文献中记录(至少明确地)。
不行,因为多加一层&
会导致失败:
fn oops() {
let a: &[i32; 3] = &[1, 2, 3];
let _b: &&[i32] = &a;
}
error[E0308]: mismatched types
--> src/lib.rs:8:23
|
8 | let _b: &&[i32] = &a;
| ------- ^^ expected slice `[i32]`, found array `[i32; 3]`
| |
| expected due to this
|
= note: expected reference `&&[i32]`
found reference `&&[i32; 3]`
此外,[T; n]
与 &[T; n]
强制转换为 [T]
的情况不同强制 &[T]
。您链接的文档描述了与未调整大小的强制转换相关的两个特征:Unsize
和 CoerceUnsized
。 [T; n]
实现了 Unsize<[T]>
,并且 因此 &[T; n]
实现了 CoerceUnsized<&[T]>
;这本质上是同一件事,您的代码有效地展示了两者。如果不使用引用(或某种类型的指针),就不可能编写一个将 [T; n]
强制转换为 [T]
的函数,因为缩小强制只发生在一些后面一种指针。