Can get guessing game example from The Book to run but not to compile

I'm able to get the guessing game example from The Book to run (via cargo run) but not to compile (via rustc). Here are the code and errors:

use rand::Rng;
use std::cmp::Ordering;
use std::io::stdin;

fn main() {
    println!("Guess the number!");

    let secret_number: i32 = rand::thread_rng().gen_range(1..101);

    println!("The secret number is {}.", secret_number);

    println!("Please input your guess: ");

    let mut guess: String = String::new();

        .read_line(&mut guess)
        .expect("Failed to read line.");

    let guess: i32 = guess.trim().parse().expect("Please type a number!");

    println!("You guessed: {}", guess);

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small."),
        Ordering::Equal => println!("You win!"),
        Ordering::Greater => println!("Too large."),


rand = "0.8.3"

errors from rustc src/

error[E0432]: unresolved import `rand`
 --> src/
1 | use rand::Rng;
  |     ^^^^
  |     |
  |     unresolved import
  |     help: a similar path exists: `io::sys::rand`

error[E0433]: failed to resolve: use of undeclared crate or module `rand`
 --> src/
8 |     let secret_number: i32 = rand::thread_rng().gen_range(1..101);
  |                              ^^^^ use of undeclared crate or module `rand`

I'm still very new to Rust (this is the second chapter of the introductory book) and so haven't been able to troubleshoot those errors. Could someone help me?

It's because the rustc cli is a huge beast and not meant to be invoked directly by most people. We have a first party build tool called cargo. If you want to build a executable without running it, use cargo build. If you want more info about it checkout the cargo book. Though you may not need it yet at this stage.

cargo build runs but doesn't appear to create an executable file

Are you on windows? If so it should create an executable at PROJECT_DIR\target\debug\PROJECT_NAME.exe

1 Like

In case if you missed, here's the book chapter which describes it.

1 Like

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.