对于所有类型"T","U",如果将"T"强制转换为"U",然后将“& T"强制转换为“&

编程入门 行业动态 更新时间:2024-10-28 14:32:37
本文介绍了对于所有类型"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",然后将“&am

本文发布于:2023-09-23 08:47:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466893.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   这是   类型   quot   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!