casting - `as` 允许进行哪些转换?

标签 casting rust

The Rust Book section on the as operator目前说

The as keyword does basic casting:

let x: i32 = 5;

let y = x as i64;

It only allows certain kinds of casting, however.

那些某些类型允许的转换是什么?

此处已删除的答案解释说,有时您需要链接多个 as-casts 才能获得安全的结果,这不能在一个步骤中完成。什么时候需要?

最佳答案

我认为这没有很好的记录,但是 here是一些您可能会觉得有用的信息:

A cast e as U is valid if one of the following holds:

  • e has type T and T coerces to U; coercion-cast
  • e has type *T, U is *U_0, and either U_0: Sized or unsize_kind(T) = unsize_kind(U_0); ptr-ptr-cast
  • e has type *T and U is a numeric type, while T: Sized; ptr-addr-cast
  • e is an integer and U is *U_0, while U_0: Sized; addr-ptr-cast
  • e has type T and T and U are any numeric types; numeric-cast
  • e is a C-like enum and U is an integer type; enum-cast
  • e has type bool or char and U is an integer; prim-int-cast
  • e has type u8 and U is char; u8-char-cast
  • e has type &[T; n] and U is *const T; array-ptr-cast
  • e is a function pointer type and U has type *T, while T: Sized; fptr-ptr-cast
  • e is a function pointer type and U is an integer; fptr-addr-cast

where &.T and *T are references of either mutability, and where unsize_kind(T) is the kind of the unsize info in T - the vtable for a trait definition (e.g. fmt::Display or Iterator, not Iterator<Item=u8>) or a length (or () if T: Sized).

Note that lengths are not adjusted when casting raw slices - T: *const [u16] as *const [u8] creates a slice that only includes half of the original memory.

Casting is not transitive, that is, even if e as U1 as U2 is a valid expression, e as U2 is not necessarily so (in fact it will only be valid if U1 coerces to U2).

关于casting - `as` 允许进行哪些转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884114/

相关文章:

memory-management - 有没有办法为大型 Rust 分配预填充操作系统的页表?

java - 解释这个关于对象引用转换的输出?

c++ - C++ 中的删除运算符是否需要正确的类型?

c# - c#中的整数数学

vb.net - 类型转换通用类型

rust - 哪些 Rust 数据结构是非确定性的

rust - 为什么 Weak::new() 不起作用而 Rc::downgrade() 起作用?

typescript - 如何在 TypeScript 中将 URL 对象与 Fetch API 一起使用?

rust - Rust 宏可以设置变量并同时返回值吗?

rust - 也许在结构方法内移动字段