DanielKeep / cargo-script

Cargo script subcommand
Other
729 stars 37 forks source link

Do we need extern crates? #78

Open SimonHeffer opened 4 years ago

SimonHeffer commented 4 years ago

Hi, rust-nooby here. I've tried scriptifying the guessing game from the Rust language book which does not use extern crates at all. From reading up the .toml seems to handle this now. Anyway I have issues find the dependencies(?) and wonder what step i've missed and whther I need to add extern crates. Here's the code:

#!/usr/bin/env run-cargo-script
//! ```cargo
//! [dependencies]
//! rand = "0.5.5"
//! gethostname = "0.2.1"
//! ```

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

fn main() {
    println!("Guess the number!");
    let secret_number = rand::thread_rng().gen_range(1, 101);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

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

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => break,
        };

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

                match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
// try hostname lib
    let h = gethostname();
    println!("Your hostname is: {:?}", h);
}

and here's(excerpt) what i get when I run the script:

$ guess.rs
    Updating crates.io index
   Compiling guess v0.1.0 (<myhomedir>.cargo/script-cache/file-guess-6c6fd683cd4e4540)
error[E0432]: unresolved import `rand`
 --> guess.rs:8:5
  |
8 | use rand::Rng;
  |     ^^^^ maybe a missing crate `rand`?

error[E0432]: unresolved import `gethostname`
  --> guess.rs:10:5
   |
10 | use gethostname::gethostname;
   |     ^^^^^^^^^^^ maybe a missing crate `gethostname`?

The unscriptified code complies and runs using cargo run. What have I missed here?

burdges commented 3 years ago

Appears extern crate no longer works in cargo script.