Calling methods directly on structs

I'm surprised that the example at the top of this page works and I would like to understand why:

use rand::distributions::{Alphanumeric, DistString};
let string = Alphanumeric.sample_string(&mut rand::thread_rng(), 16);

Alphanumeric is a struct that implements the DistString trait. DistString declares sample_string() like this:

fn sample_string<R: Rng + ?Sized>(&self, rng: &mut R, len: usize) -> String { ... }

I thought that sample_string() would have to be called on an instance of Alphanumeric but in this example it appears to be called on the Alphanumeric struct itself.

Similar to how tuple structs have a same-named tuple constructor...

struct Tuple(i32, u32);
fn main() {
    let tuple = Tuple(0, 0);
    let constructor: fn(i32, u32) -> Tuple = Tuple;

...unit structs have a same-named const-like value you can use.

struct Unit;
fn main() {
    let unit: Unit = Unit;

The example you quoted is just using such a value in place.


Ah, I see! Thanks for explaining.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.