Skip to content

Commit

Permalink
feat: rpt 31 - enum size
Browse files Browse the repository at this point in the history
  • Loading branch information
encody committed Nov 23, 2023
1 parent bbe7f4b commit b8df3c4
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion content/blog/rust-pro-tips-collection.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: "Rust Pro Tips (collection)"
date: 2023-04-08
lastmod: 2023-09-14
lastmod: 2023-11-23
description: "Level up your Rust skills."
author: Jacob Lindahl
twitter: sudo_build
Expand All @@ -12,6 +12,33 @@ 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.

## 31. Use indirection in enums to save memory

<!-- [Tweet]() [Toot]() -->

All variants of an enum are the same size. This can become a problem when variants have drastically different memory requirements. Use indirection (`&`-reference, `Box`, etc.) to resolve.

```rust
enum WithoutIndirection {
Unit,
Kilobyte([u8; 1024]),
}

enum WithIndirection<'a> {
Unit,
Kilobyte(&'a [u8; 1024]),
}

println!("{}", std::mem::size_of_val(&WithoutIndirection::Unit));
// => 1025

println!("{}", std::mem::size_of_val(&WithIndirection::Unit));
// => 8
```

[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bee0edb5a4b888c8c9d3df0e473246cc) \
[Docs](https://doc.rust-lang.org/reference/types/enum.html)

## 30. Create a slice from a reference without copying

[Tweet](https://twitter.com/sudo_build/status/1702009293850165747) [Toot](https://infosec.exchange/@hatchet/111058977026865657)
Expand Down

0 comments on commit b8df3c4

Please sign in to comment.