From 45bb2de220c9522cd623acaafc085e0a497470d8 Mon Sep 17 00:00:00 2001 From: Martin Geisler <mgeisler@google.com> Date: Tue, 3 Dec 2024 16:57:41 +0100 Subject: [PATCH] Recommend newtypes over type aliases (#2476) I don't know how controversial this is, but I would recommend against using type aliases where a newtype can be used instead. Personally, I don't like type aliases much since I feel they cause extra indirection: I will inevitably have to go look up the alias the first many times I encounter it. Nothing will tell me to apply the type alias consistently, and I dislike having multiple names for the same thing. But I'm sure some people love them, so now I'm just gently reminding people that newtypes can be a better alternative. --- src/user-defined-types/aliases.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/user-defined-types/aliases.md b/src/user-defined-types/aliases.md index 4c998dd8..48759028 100644 --- a/src/user-defined-types/aliases.md +++ b/src/user-defined-types/aliases.md @@ -23,6 +23,10 @@ type PlayerInventory = RwLock<Vec<Arc<RefCell<Item>>>>; <details> -C programmers will recognize this as similar to a `typedef`. +- A [newtype](tuple-structs.html) is often a better alternative since it creates + a distinct type. Prefer `struct InventoryCount(usize)` to + `type InventoryCount = usize`. + +- C programmers will recognize this as similar to a `typedef`. </details>