Skip to content

Commit

Permalink
Add size_of and size_of_val to the prelude
Browse files Browse the repository at this point in the history
Many, many projects use `size_of` to get the size of a type. However,
it's also often equally easy to hardcode a size (e.g. `8` instead of
`size_of::<u64>()`). Minimizing friction in the use of `size_of` helps
ensure that people use it and make code more self-documenting.

The name `size_of` is unambiguous: the name alone, without any prefix or
path, is self-explanatory and unmistakeable for any other functionality.
Adding it to the prelude cannot produce any name conflicts, as any local
definition will silently shadow the one from the prelude. Thus, we don't
need to wait for a new edition prelude to add it.
  • Loading branch information
joshtriplett committed Mar 28, 2024
1 parent 4ea92e3 commit bfa36cd
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
3 changes: 3 additions & 0 deletions library/std/src/prelude/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ pub use crate::ops::{Drop, Fn, FnMut, FnOnce};
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)]
pub use crate::mem::drop;
#[stable(feature = "size_of_prelude", since = "CURRENT_RUSTC_VERSION")]
#[doc(no_inline)]
pub use crate::mem::{size_of, size_of_val};

// Re-exported types and traits
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
2 changes: 2 additions & 0 deletions library/std/src/prelude/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
//! operations for both destructors and overloading `()`.
//! * <code>[std::mem]::[drop]</code>, a convenience function for explicitly
//! dropping a value.
//! * <code>[std::mem]::{[size_of], [size_of_val]}</code>, to get the size of
//! a type or value.
//! * <code>[std::boxed]::[Box]</code>, a way to allocate values on the heap.
//! * <code>[std::borrow]::[ToOwned]</code>, the conversion trait that defines
//! [`to_owned`], the generic method for creating an owned type from a
Expand Down

0 comments on commit bfa36cd

Please sign in to comment.