rust 32 lines · 6 steps

A newtype wrapper for API tokens in Rust

Wrapping a String in a dedicated type gives cryptographically random API tokens a safe, self-documenting API.

Explained by highlit
1use rand::distributions::{Alphanumeric, DistString};
2use rand::rngs::OsRng;
3 
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct ApiToken(String);
6 
7impl ApiToken {
8 const DEFAULT_LEN: usize = 40;
9 
10 pub fn generate() -> Self {
11 Self::with_len(Self::DEFAULT_LEN)
12 }
13 
14 pub fn with_len(len: usize) -> Self {
15 let raw = Alphanumeric.sample_string(&mut OsRng, len);
16 ApiToken(format!("sk_{raw}"))
17 }
18 
19 pub fn as_str(&self) -> &str {
20 &self.0
21 }
22 
23 pub fn into_inner(self) -> String {
24 self.0
25 }
26}
27 
28impl std::fmt::Display for ApiToken {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.write_str(&self.0)
31 }
32}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The newtype pattern turns a bare String into a distinct type the compiler can enforce, preventing accidental misuse.
  2. 2Using OsRng ensures tokens draw from the operating system's cryptographically secure randomness rather than a predictable PRNG.
  3. 3Exposing narrow accessors like as_str and into_inner keeps the inner value controlled instead of publicly mutable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A newtype wrapper for API tokens in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code