对于所有类型"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`?

查看:72
本文介绍了对于所有类型"T","U",如果将"T"强制转换为"U",然后将“& T"强制转换为“& U",这是真的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有据可查 [T;n] 可以强制转换为 [T] .以下代码也是格式正确的:

It's 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] .

Here we have that &[T; n] is coerced to &[T].

对于所有类型的 T ,如果 T 强制为 U ,则 U 是否为 U >& T 被强制为& U ?

Is it true that for all types T, U if T is coerced to U then &T is coerced to &U?

参考文献中没有对此进行记录(至少是明确记录).

It's not documented in the reference (at least explicitly).

推荐答案

否,因为再增加一层& 会导致失败:

No, because adding one more layer of & causes it to fail:

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] .您链接的文档描述了与未定大小强制有关的两个特征: Unsize CoerceUnsized . [T;n] 实现 Unsize< [T]> ,因此因此 & [T;n] 实现 CoerceUnsized<& [T]> ;这本质上是同一件事,并且您的代码有效地展示了两者.不可能编写强制 [T;n] [T] 而没有使用引用(或某种类型的指针),因为取消大小调整的强制仅发生在某种类型的指针后面.

Further, it is not the case that [T; n] coerces to [T] in the same sense that &[T; n] coerces to &[T]. The documentation you linked describes the two traits related to unsized coercions: Unsize and CoerceUnsized. [T; n] implements Unsize<[T]>, and therefore &[T; n] implements CoerceUnsized<&[T]>; this is essentially the same thing, and your code effectively demonstrates both. It would not be possible to write a function that coerces [T; n] to [T] without using references (or pointers of some sort) because unsizing coercions only take place behind some kind of pointer.

这篇关于对于所有类型"T","U",如果将"T"强制转换为"U",然后将“&amp; T"强制转换为“&amp; U",这是真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆