所有原始类型都实现了 Copy 特性吗? [英] Do all primitive types implement the Copy trait?

查看:38
本文介绍了所有原始类型都实现了 Copy 特性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否所有 Rust 中的原始类型都实现了Copy 特质?

Do all primitive types in Rust implement the Copy trait?

了解这一点会很有趣,因为这些知识肯定是彻底学习新编程语言的一部分.

It would be interesting to know, as surely such knowledge is part of a thorough learning of a new programming language.

推荐答案

我们可以使用编译器来证明某些东西是否实现了Copy.使用来自The Rust 的原语列表编程语言:

We can use the compiler to prove if something implements Copy. Using 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()>();
}

还有一些其他类型我认为是原始的":

There are a few other types I'd consider "primitive":

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

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

Immutable references always implement Copy, mutable references never implement Copy, and raw pointers always implement Copy:

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

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

There are a few other types from the book's list:

  • 元组
  • 数组

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

These types can contain many types; they are parameterized over a generic. They are only Copy if all the contained values are 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).未调整大小的值不能单独存在.引用背后的版本表现得像引用一样.

    Slices are doubly special. The slice type itself ([T]) and string slices (str) are unsized types. It's very rare to see them without an indirection of some kind, often a reference (&[T] / &str). The unsized values cannot exist by themselves. The version behind a reference behaves like references do.

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

    和往常一样,特性的 文档列出了实现该特性的所有内容特质.(除非文档中存在错误).

    And as always, the documentation for a trait lists everything that implements that trait. (Except when there are bugs in the documentation).

    这篇关于所有原始类型都实现了 Copy 特性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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