Rust Examples – How to Generate Unique String IDs

How to generate unique URL-friendly string IDs in Rust

This piece will explore Rust examples involving generation or random but unique string IDs.

(a). use nanoid

This a tiny, secure, URL-friendly, unique string ID generator for Rust.

Step 1: Install it

Start by installing it. Add the following to your Cargo.toml file:

nanoid = "0.4.0"

Step 2: Write Code

Here are simple examples showing you how to use nanoid to generate unique IDs:

Example 1: Simple

The main module uses URL-friendly symbols (A-Za-z0-9_-) and returns an ID with 21 characters.

use nanoid::nanoid;

fn main() {
   let id = nanoid!(); //=> "Yo1Tr9F3iF-LFHX9i9GvA"

Symbols -,.() are not encoded in the URL. If used at the end of a link they could be identified as a punctuation symbol.

Example 2: with custom length

If you want to reduce ID length (and increase collisions probability), you can pass the length as an argument generate function:

use nanoid::nanoid;

fn main() {
   let id = nanoid!(10); //=> "IRFa-VaY2b"

Example 3: Custom Alphabet or Length

If you want to change the ID's alphabet or length, you can simply pass the custom alphabet to the nanoid!() macro as the second parameter:

use nanoid::nanoid;

fn main() {
    let alphabet: [char; 16] = [
        '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'

   let id = nanoid!(10, &alphabet); //=> "4f90d13a42"

Alphabet must contain 256 symbols or less. Otherwise, the generator will not be secure.

Example 4: Custom Random Bytes Generator

You can replace the default safe random generator using the complex module. For instance, to use a seed-based generator.

use nanoid::nanoid;

fn random_byte () -> u8 { 0 }

fn main() {
    fn random (size: usize) -> Vec<u8> {
        let mut bytes: Vec<u8> = vec![0; size];

        for i in 0..size {
            bytes[i] = random_byte();


    nanoid!(10, &['a', 'b', 'c', 'd', 'e', 'f'], random); //=> "fbaefaadeb"


Number Link
1. Read more
2. Follow crate author
3. Docs

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *