rust - 是否所有原始类型都实现了 Copy 特性?

标签 rust

全部primitive types in Rust实现 Copy 特性?

知道这一点会很有趣,因为这些知识肯定是全面学习新编程语言的一部分。

最佳答案

我们可以使用编译器来证明某些东西是否实现了Copy。使用the list of primitives from The Rust Programming Language :

fn is_copy<T: Copy>() {}

fn main() {
    is_copy::<bool>();
    is_copy::<char>();
    is_copy::<i8>();
    is_copy::<i16>();
    is_copy::<i32>();
    is_copy::<i64>();
    is_copy::<u8>();
    is_copy::<u16>();
    is_copy::<u32>();
    is_copy::<u64>();
    is_copy::<isize>();
    is_copy::<usize>();
    is_copy::<f32>();
    is_copy::<f64>();
    is_copy::<fn()>();
}

还有一些我认为是“原始”的类型:

  • 不可变引用(&T)
  • 可变引用(&mut T)
  • 原始指针(*const T/*mut T)

不可变引用总是实现Copy,可变引用从不实现Copy,而原始指针总是实现Copy:

// OK
is_copy::<&String>();
is_copy::<*const String>();
is_copy::<*mut String>();
// Not OK
is_copy::<&mut i32>();

本书列表中还有一些其他类型:

  • 元组
  • 数组

这些类型可以包含很多类型;它们是通过泛型参数化的。如果所有包含的值都是Copy,它们只是Copy:

// OK
is_copy::<[i32; 1]>();
is_copy::<(i32, i32)>();
// Not OK
is_copy::<[Vec<i32>; 1]>();
is_copy::<(Vec<i32>, Vec<i32>)>();
  • 切片

切片具有双重特殊性。切片类型本身 ([T]) 和字符串切片 (str) 是 unsized 类型。很少看到它们没有某种间接性,通常是引用 (&[T]/&str)。未调整大小的值不能单独存在。引用背后的版本表现得像引用一样。

// OK
is_copy::<&str>();
is_copy::<&[i32]>();
// Not OK
is_copy::<str>();
is_copy::<[i32]>();

和往常一样,documentation for a trait lists everything that implements that trait . (除非有 bugs in the documentation )。

关于rust - 是否所有原始类型都实现了 Copy 特性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41413336/

相关文章:

rust - 使用 Sled,我如何序列化和反序列化?

rust - 如何在所有子命令都为可选的情况下创建StructOpt命令

rust - 有没有比匹配更好的方法来访问相同类型的枚举值?

rust - 如何测试特征对象之间的相等性?

rust - 如何将可见性 token 传递给位标志!宏?

struct - 我如何声明我想要一个包含对实现特征的东西的引用的结构?

rust - 了解 Rc<RefCell<SomeStruct>> 在 Rust 中的用法

json - 我可以使用类型来表示构造函数的至少一个参数应该是 Some 吗?

rust - FromStr & FromErr 解析字符串时出现问题

rust - 为 FFI 返回具有生命周期的结构