I'm confused by undeclared type error for rand

If I put all of the code in main, it works with an (I believe) incorrect warning. When compiled as a separate module, I get the error. The unused import warning occurs when I put everything in main, and the program works.

First, the compiler output:

cargo run
Compiling rand-test v0.1.0 (.../rand-test)
error[E0433]: failed to resolve. Use of undeclared type or module rand
--> src/ra.rs:14:19
|
14 | let mut rng = rand::thread_rng();
| ^^^^ Use of undeclared type or module rand

warning: unused import: rand::thread_rng
--> src/ra.rs:1:5
|
1 | use rand::thread_rng;
| ^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default

error: aborting due to previous error

error: Could not compile rand-test.

To learn more, run the command again with --verbose.

Second, the contents of the module:

use rand::thread_rng;
use rand::distributions::{IndependentSample, Range};

static COOKIE_CHARS : [char; 62] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

pub fn get_session_string() -> String {
let mut result = String::new();
let random_index = Range::new(0, COOKIE_CHARS.len());

let mut rng = rand::thread_rng();


for _index in 0..2 {
    let char = random_index.ind_sample(&mut rng);
    result.push(COOKIE_CHARS[char]);
}

result

}

Now, main.rs
extern crate rand;

mod ra;
use ra::*;

fn main() {

println!("{}", get_session_string());

}

Finally, the contents of Cargo.toml:

[package]
name = "rand-test"
version = "0.1.0"
authors = ["zweig"]

[dependencies]
rand = "0.3"

I'm pretty confused, as it looks like it should be right. Moving the code to main shouldn't solve the problem, and the fact that the unused import warning stays when in main is very confusing.

Thanks for any help,
zweig

In your module, you should either use rand; and then reference the function as you have, rand::thread_rng(), or import the function using use rand::thread_rng and then call it with just thread_rng(). Right now you’re importing just the function but then using the full path when calling it.

The unused import warning is because of the above. The code compiles when in main.rs because you’ve made the module available via extern crate rand.

1 Like

Thanks. That works.

As I think this message board is at least somewhat tied to the Rust project, it might be useful if I link to the example which lead me astray.

https://doc.rust-lang.org/rand/rand/index.html#functions

I assume that there is an implied use declaration in the example, as they are using rand::thread-rng, without having a "use rand;"

Thanks again.