Storing a uniform distribution in a struct

Hello everyone,

I'm quite new to Rust programming so I hope this is not a dumb question. I want to make a struct with a function that samples random numbers from a uniform distribution. To avoid having to create the distribution every time, I am trying to store it in a variable like so:

impl StructWithDistribution {
	fn new() -> StructWithDistribution {
		dist: Uniform::from(0..7);
	}
}

The struct has more fields, but I have omitted these for now. What I can't figure out is how I should define the type of dist. When I try

pub struct StructWithDistribution {
	dist: Uniform
}

I get the error expected 1 generic argument. I have also tried dist: Uniform<usize>, but that gives the error expected type, pointing to the 0 in dist: Uniform::from(0..7).

Anyone any idea? Thanks in advance for the help!

In the body of your new function, you need to wrap the dist field in a StructWithDistribution { ... } literal:

	fn new() -> StructWithDistribution {
		StructWithDistribution { dist: Uniform::from(0..7) }
	}

You can also use Self instead of repeating the struct name, which might make this easier to read:

	fn new() -> Self {
		StructWithDistribution { dist: Uniform::from(0..7) }
	}

Ahhhh big facepalm. This got me scratching my had for way too long, totally did not see that I missed it. Thank you!

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.