Rust入门问题: use of undeclared crate or module `rand`

按照官网学rust,程序地址在这里,

写个猜数字游戏 - Rust 程序设计语言 简体中文版

程序内容也很简单,

rust 复制代码
use std::io;
use rand::Rng;

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

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

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

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

    let mut guess = String::new();

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

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

然后,程序运行时报错:

use of undeclared crate or module `rand`

原因:

运行程序找不到库,或者叫依赖(rust里有crates, package, module,看字面理解吧)

解决办法:

在cargo.toml中dependencies添加一条:

rand="0.8.5" ,如下,

XML 复制代码
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"

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

[dependencies]
rand="0.8.5"

这里0.8.5是指版本,跟你的rust的版本有关。

本文结束。

相关推荐
万少7 小时前
小龙虾(openclaw),轻松玩转自动发帖
前端·人工智能·后端
Jagger_8 小时前
AI 洪水淹到脖子了:剩下的是什么?我们该往哪儿跑?
后端
Victor3569 小时前
MongoDB(28)什么是地理空间索引?
后端
Victor35610 小时前
MongoDB(29)如何创建索引?
后端
皮皮林55110 小时前
面试官:什么是 fail-fast?什么是 fail-safe?
后端
陈随易11 小时前
前端大咖mizchi不满Rust、TypeScript却爱上MoonBit
前端·后端·程序员
雨中飘荡的记忆13 小时前
Multi-Agent + Skills + Spring AI 构建自主决策智能体
后端·spring
我叫黑大帅13 小时前
Go 语言并发编程的 “工具箱”
后端·面试·go
用户83562907805114 小时前
Python 实现 PowerPoint 形状动画设置
后端·python