Reputation: 105
I'm a rust newbie and I wanted to understand why Rust is throwing me an error when I run the following code:
let rng = rand::thread_rng();
const NUMBER_TO_GUESS: u32 = rng.gen();
Error:
error[E0435]: attempt to use a non-constant value in a constant
--> src/main.rs:12:34
|
12 | const NUMBER_TO_GUESS: u32 = rng.gen();
| --------------------- ^^^ non-constant value
| |
| help: consider using `let` instead of `const`: `let NUMBER_TO_GUESS`
Upvotes: 3
Views: 5221
Reputation: 1179
If you really want a const
(generated during compile time and does not change each time the program is run), then cargo add const-random
and use the following:
use const_random::const_random;
fn main() {
const NUMBER_TO_GUESS: u32 = const_random!(u32);
println!("Hello {}", NUMBER_TO_GUESS);
}
I see that the variable is named NUMBER_TO_GUESS
. A guessing game should probably change the number on each run, so you would use the following:
use rand::Rng;
fn main() {
// rng needs to be mut because it needs to be modified so that
// rng.gen() returns different values each time
let mut rng = rand::thread_rng();
let number_to_guess: u32 = rng.gen();
println!("Hello {}", number_to_guess);
}
I see in the comments you are from Javascript. Here is a table with some roughly corresponding syntax:
Typescript | Rust |
---|---|
let x: Something = y; |
let mut x = y; |
let x: Readonly<Something> = y; |
let mut x = &y; |
const x: Something = y; |
let x = &mut y; |
const x: Readonly<Something> = y; |
let x = y; |
Closest is Webpack's EnvironmentPlugin/DefinePlugin with const x: string = process.env.SOMETHING; plus a minifier |
const x = "That thing"; |
In the Rust code you have, you see let rng
before const NUMBER_TO_GUESS
. The compiler does not see it this way. Ahead-of-time compiled languages always calculate the const
one before other variables.
Upvotes: 5