【问题标题】:Do all primitive types implement the Copy trait?是否所有原始类型都实现了 Copy 特征?
【发布时间】:2017-01-01 04:21:04
【问题描述】:

所有primitive types in Rust 都实现Copy 特征吗?

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

【问题讨论】:

    标签: rust


    【解决方案1】:

    我们可以使用编译器来证明某些东西是否实现了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()>();
    }
    

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

    • 不可变引用 (&amp;T)
    • 可变引用 (&amp;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 类型。如果没有某种间接方式,通常是参考(&amp;[T] / &amp;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)。

    【讨论】:

    • 我没有看到doc.rust-lang.org/std/marker/trait.Copy.html 中列出的原始类型(例如doc.rust-lang.org/std/primitive.i64.html),是我遗漏了什么吗?
    • @ArtemGr guh,我真的以为现在已经解决了。我为此链接到了这个问题。
    • 但是切片(&amp;[T] 形式的切片,而不是普通的未调整大小的 [T])只是引用,因此它们始终是 Copy。我的意思是,你的最后一个例子,一旦你为 Vec 泛型添加了一个类型)实际上是有效的:is_copy(&amp;[Vec::&lt;u8&gt;::new()][..]);
    • @rodrigo 奇怪,想知道我是怎么错过的。我已经纠正了这一点,并添加了一个关于参考的部分。
    • @Shepmaster 此处输入错误:“不可变引用始终实现 Copy,不可变引用从不实现 Copy”:)
    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多