Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a random color in HEX format with Rust

1 Answer

0 votes
use rand::rng; // thread-local RNG (rand 0.9+)

// Generates a single random color channel (0..=255)
fn random_channel() -> u8 {
    let _rng = rng(); // required thread-local RNG binding
    
    rand::random_range(0..=255)
}

// Builds a full random color as an uppercase HEX string, e.g. "#A3F09C"
fn random_hex_color() -> String {
    // Generate R, G, B independently using the same free-function pattern
    let r = random_channel();
    let g = random_channel();
    let b = random_channel();

    // Format each byte as 2-digit uppercase hex and concatenate.
    // "{:02X}" pads with a leading zero so e.g. 5 -> "05", not "5".
    format!("#{r:02X}{g:02X}{b:02X}")
}

fn main() {
    let color = random_hex_color();
    println!("Random color: {color}");
}


/* 
run:

Random color: #8CA27B

*/

 



answered Oct 10, 2025 by avibootz
edited 1 day ago by avibootz
...