Noob: How to use function within Trait Implementation


#1

How do I call a function within Trait Implementations? Method functions appear to be visible but for trying, I can’t seen to get sight of the traits.

So, for example, how do I print a random number by using [gen_range() or gen()] from the rand::OsRng?

impl Rng for OsRng
fn gen<T: Rand>(&mut self) -> T
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T
from http://doc.rust-lang.org/rand/rand/struct.OsRng.html


#2

You’ll have to create an instance of the OsRng class, i.e.

rng = OsRng::new().unwrap();
let num: f64 = rng.gen();
...

#3

Thanks!

Works as:

extern crate rand;
fn main() {
use rand::OsRng;
use rand::Rng;
let mut rg = OsRng::new().unwrap();
let num: f64 = rg.gen();
println!("{}", num);
}


#4

Nice! In a real app you’ll probably want to replace the unwrap() call by real error handling :smile:

Another tip: if you use triple-backquotes around your code blocks you’ll get nice highlighting and correct indentation.


#5

I got an instance of each function working but I don’t understand why

rng.choose(&choices)

produces output as

Some(value)

and not just the value.

Also, I note the Example html anchors in the docs are all pointed to the same url, which perhaps would be better with some index for each of them… in that page of examples then all point to http://doc.rust-lang.org/rand/rand/trait.Rng.html#example but many of those.


#6

The doc says: “Return None if values is empty.” Since Rust doesn’t have a type of slice that is guaranteed to be nonempty, this failure case has to be considered, and it’s better than panicking. This is actually a good case for using unwrap() if you pass a choices array that you know is not empty, e.g. if it’s a constant.

(I’ve already pointed out the problem with the URLs once, but I guess it’s low priority.)


#7

Yay! It’s all starting to make sense! :smile:

rng.choose(&choices).unwrap()