From 61a79dbcae1cd6113f5cca6894850f0faa0165f4 Mon Sep 17 00:00:00 2001 From: Jacob Date: Thu, 14 Sep 2023 02:14:44 +0900 Subject: [PATCH] feat: slice from reference rpt --- content/blog/rust-pro-tips-collection.md | 26 +++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/content/blog/rust-pro-tips-collection.md b/content/blog/rust-pro-tips-collection.md index 890e4c9..c912890 100644 --- a/content/blog/rust-pro-tips-collection.md +++ b/content/blog/rust-pro-tips-collection.md @@ -1,7 +1,7 @@ --- title: "Rust Pro Tips (collection)" date: 2023-04-08 -lastmod: 2023-08-29 +lastmod: 2023-09-14 description: "Level up your Rust skills." author: Jacob Lindahl twitter: sudo_build @@ -12,6 +12,30 @@ license: This is a collection of Rust "pro tips" that I've collected, most of which have been [posted on Twitter](https://twitter.com/search?q=%23RustProTip%20%40sudo_build&src=typed_query&f=top). I'll keep updating this post as I write more. Tips are ordered in reverse chronological order, with the most recent ones at the top. +## 30. Create a slice from a reference without copying + + + +If you have a reference to some data and you want to pass it to a function that takes a slice, you can use [`std::array::from_ref`](https://doc.rust-lang.org/std/array/fn.from_ref.html) to cheaply create a slice without copying. + +```rust +struct Thing; + +fn takes_slice(_: &[Thing]) { + // ... +} + +fn my_function(arg: &Thing) { + takes_slice(std::array::from_ref(arg)); +} + +fn main() { + my_function(&Thing); +} +``` + +[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=76925f46c4aaceb7c39c3d58030ae0a4) + ## 29. Include README in documentation [Tweet](https://twitter.com/sudo_build/status/1696353871088803917) [Toot](https://infosec.exchange/@hatchet/110970596795877242)