Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

rust - Do all primitive types implement the Copy trait?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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":

  • Immutable references (&T)
  • Mutable references (&mut T)
  • Raw pointers (*const T / *mut T)

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:

  • Tuples
  • Arrays

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>)>();
  • Slices

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...