O'Reilly logo

Rust Standard Library Cookbook by Daniel Durante, Jan Nils Ferner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How it works...

Before you can use rand, you have to tell Rust that you're using the crate by writing:

extern crate rand;

After that, rand will provide a random generator. We can access it by either calling rand::random(); [6] or by accessing it directly with rand::thread_rng(); [22].

If we go the first route, the generator will need to be told what type to generate. You can either explicitly state the type in the method call [6] or annotate the type of the resulting variable [8]. Both are equal and result in the exact same thing. Which one you use is up to you. In this book, we will use the first convention.

As you can see in lines [29 and 33], you need neither if the type is unambiguous in the called context.

The generated value will be ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required