In current rand 0.10.3, use rand::rng() to obtain the thread-local random-number generator, then call methods such as random() and random_range(...) on a mutable local handle. The older-looking thread_rng name is a version clue: check which rand release your project uses before copying examples written for another API version.
Use rand::rng() in current rand
The current rand documentation identifies rand::rng() as the accessor for a handle to the current thread’s ThreadRng. Import RngExt, bind the handle as mutable, and use its methods to generate values. This example produces a random boolean and an integer from 1 through 6:
use rand::RngExt;
fn main() {
let mut rng = rand::rng();
let coin_flip: bool = rng.random();
let die_roll: i32 = rng.random_range(1..=6);
println!("{coin_flip}, {die_roll}");
}
The example follows the current rand 0.10.3 API documented for rand::rng(). The handle is mutable because these calls advance the generator’s state.
Check the version in your project
The function name in an example is not enough to identify which rand API it targets. If code using thread_rng() appears in a tutorial or an older codebase, compare it with the version specified in your project’s Cargo.toml and lockfile, then consult the documentation for that version. The examples here are for the current 0.10.3 documentation; they are not a claim that every historical rand release uses the same names or imports.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
#1 Best Overall
Keep dependency selection and API selection aligned. The exact dependency declaration and feature configuration depend on the project; check the versioned crate documentation and your Cargo configuration rather than changing a dependency blindly to make an example compile.
Generate values and numbers in a range
random() infers its output type from the place where you use the result. Give the value an explicit type when inference is unclear. The following examples use the same local generator:
use rand::RngExt;
let mut rng = rand::rng();
let value: u8 = rng.random();
let fraction: f64 = rng.random();
let die = rng.random_range(1..=6);
random_range takes a Rust range. Use 1..=6 when both endpoints should be possible; the inclusive range operator = is important for a six-sided die. Use 1..6 when the upper bound should be excluded. Choose a range whose bounds are valid for the type and whose interval contains values.
Use the convenience functions for occasional calls
For a simple one-off value, rand also documents free functions such as rand::random() and rand::random_range(...). The latter is shorthand for obtaining the thread-local generator and calling its random_range method. These can make a small expression more concise.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #2
When generating repeatedly, retain one local handle instead of repeatedly calling a convenience function. The rand documentation recommends this pattern to avoid an initialization check on every use. It is an API-usage recommendation, not a published benchmark or a guarantee of a particular speedup.
Reuse the handle for repeated work
Bind the generator in the function or scope that performs the repeated work, then pass a mutable reference to helper functions that need it. For example, the shuffle method takes a mutable generator handle:
use rand::RngExt;
fn main() {
let mut rng = rand::rng();
let mut cards = ["A", "2", "3", "4", "5", "6"];
cards.shuffle(&mut rng);
println!("{cards:?}");
}
This keeps random-number generation explicit in the code that uses it, while avoiding creation of a new handle at each call site. The full set of applicable methods and supported types depends on the rand version and enabled features; use that version’s API docs when extending the example.
Understand ThreadRng’s thread and lifecycle limits
ThreadRng is a reference to a lazily initialized, thread-local generator. Its handle is neither Send nor Sync, so it cannot be transferred between threads or shared for concurrent use. Create or obtain a handle within the thread that will use it. If a design needs randomness in several threads, each thread should use its own thread-local handle rather than moving one handle across threads.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #3
The current ThreadRng documentation describes automatic seeding using SysRng and reseeding after every 64 kB of output. That documented interval is an implementation behavior, not a speed figure or a promise that all security needs are met. Initializing the generator can panic if the system random source fails.
Forking and reentrancy
The docs do not describe automatic reseeding after a process fork. If your application forks, explicitly reseed in the child process as the documentation recommends; do not assume the child automatically receives fresh generator state.
Calls are not reentrant-safe. Avoid calling the same generator from an interrupt unless you can rule out concurrent use of that generator. These constraints matter in low-level or process-management code even though ordinary single-threaded application code usually does not encounter them.
Choose the random source for the job
| Need | Option | What to account for |
|---|---|---|
| Convenient general-purpose randomness within a thread | rand::rng() and its ThreadRng handle |
Thread-local; not transferable between threads. Suitability depends on the threat model. |
| An interface over the operating system’s random source | SysRng |
Rand documents it as the source used to seed ThreadRng and as an alternative. See the rand RNG module overview. |
| Repeatable sequences for a task that needs reproducibility | An explicitly seeded generator | Standard generators are deterministic, but the RNG module documentation cautions that they are not portable across releases and platforms. Select and document the algorithm and version for your use case. |
Rand describes ThreadRng as using a ChaCha 12-round generator and as fast and reasonably secure, while leaving users to decide whether it fits their security requirements. Its in-memory state has no further protections and is not required to be zeroed when a process or thread exits. Do not interpret the general-purpose description as a blanket assurance for secrets, long-term key material, or every attacker model. If your requirements call for operating-system randomness, consider SysRng; define the threat model and consult the current crate documentation before choosing.
Troubleshoot common compile and runtime problems
“Cannot find function thread_rng” or “cannot find function rng”
First identify the rand version selected by Cargo. A tutorial using thread_rng may target a different release from the current 0.10.3 examples here. Conversely, code written for rand::rng() will not necessarily compile against an older release. Use the versioned documentation for the dependency you actually have, and update the dependency only if the project can accept that change.
Method not found for random or random_range
For the documented current API, bring the extension trait into scope with use rand::RngExt;. Also verify that the dependency version and selected features match the code. If a different rand release is in use, its trait names and feature requirements may differ; consult its version-specific docs instead of mixing imports from multiple examples.
Type inference fails
random() needs a result type. Add an annotation such as let value: u8 = rng.random();, or otherwise make the expected type clear from the surrounding code. For a range, ensure the bounds are compatible with the intended result type.
The range includes an unexpected number of values
Rust’s .. range excludes its upper endpoint; ..= includes it. For values 1 through 6, use 1..=6. Review both endpoints and the desired type when changing a range.
The handle cannot be sent to another thread
This is expected: ThreadRng is neither Send nor Sync. Obtain a separate thread-local handle in the thread that needs randomness rather than storing one handle in a cross-thread task or shared object.
Initialization fails
The rng() documentation notes that initial seeding can panic if SysRng fails. This is a failure of the system random source, not an invalid random range. Consider how your application should handle a panic and review the rand source documentation for the initialization path: thread RNG source.
Or skip the browser setup
This Rust example is about random-number generation; ScreenshotNeo is a separate developer tool for website screenshots, not a replacement for rand. If your project also needs a website capture, ScreenshotNeo accepts a URL in one request and returns a screenshot or PDF. See the ScreenshotNeo website and its API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo removes supported cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers indicate the page verdict and billing status. Its MCP server provides screenshot tools for AI agents, and the Free plan includes 1,000 screenshots a month without a card; paid plans start at $5 for 3,000. Sign up for the free plan.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Official references
- rand::rng()
- ThreadRng
- rand::random() and rand::random_range()
- rand RNG module overview
- Thread RNG source
Frequently Asked Questions
Does calling rand::rng() return a new generator each time?
It provides a handle to the current thread-local generator; it should not be treated as constructing an independent stream for every call.
Can I use ThreadRng directly in an async task?
It can be used where the code runs on its owning thread, but its non-Send, non-Sync handle can conflict with futures or task structures that must move between threads. Keep the handle within a suitable scope or use a different design.
Is ThreadRng suitable for generating passwords or cryptographic keys?
The documentation leaves suitability to the application’s threat model and describes limitations on in-memory protection. Review the security requirements and consider SysRng when appropriate rather than assuming ThreadRng satisfies every cryptographic use.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




