KapitaiN
KapitaiN

Reputation: 473

How to resolve "unresolved import" in Rust when using VS Code?

I'm fairly new to rust and have been following the official book that they provide on their site. During chapter 2 they tell you to import a "Rand" cargo which I did. However, when I try to run my code directly through VS Code I get an error saying "unresolved import rand". When I run it through command prompt, everything works fine. I've already tried every solution suggested here: https://github.com/rust-lang/rls-vscode/issues/513 and nothing seemed to have worked. Extensions that I'm using:

Has anyone else ran into a similar problem or a know a solution? Thank you!

Edit: My Cargo.TOML looks like this:

[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Name <[email protected]>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.6.0"

Edit 2: my main.rs file looks like this:

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

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(_) => continue,
        };
        println!("Your guess {}", guess);
        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}

Upvotes: 10

Views: 26412

Answers (1)

Jaff
Jaff

Reputation: 134

Got a fix!

In VSC, select Extensions, select the Code Runner extension, click the little gear symbol and select Extension Settings. It's the Code-runner: Executor Map setting that needs to be changed. Click the 'Edit in settings.json' link.

Add the following to the file:

"code-runner.executorMap": {
   "rust": "cargo run # $fileName"
}

If you already have content in the settings.json file then remember to add a comma to the line above and put your edit inside the outermost curly braces, e.g.

{
    "breadcrumbs.enabled": true,
    "code-runner.clearPreviousOutput": true,
    "code-runner.executorMap": {
        "rust": "cargo run # $fileName"
    }
}

This tells Code Runner to use the 'cargo run' command, instead of 'rustc'

This fix came from this question on stackoverflow.

Upvotes: 10

Related Questions