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的版本有关。

本文结束。

相关推荐
wdfk_prog9 小时前
嵌入式面试真题第 10 题:高优化等级下共享状态可见性、内存模型与系统级同步设计
java·linux·开发语言·面试·职场和发展·架构·c
谭光志11 小时前
Vibe Coding 时代,程序员该何去何从
前端·后端·ai编程
GoGeekBaird11 小时前
我用 BeeWeave 跑完了一次完整写作闭环
后端·github
仿生狮子12 小时前
别再说“全栈”了,AI 时代团队只认这 5 种人
前端·人工智能·后端
许彰午13 小时前
95_Python内存管理与垃圾回收
开发语言·python
多加点辣也没关系13 小时前
JavaScript|第13章:原始类型的方法
开发语言·javascript·ecmascript
এ慕ོ冬℘゜13 小时前
深入理解 JavaScript 事件体系:Window、鼠标与键盘事件详解
开发语言·javascript·okhttp
AOwhisky13 小时前
下一代容器来了?Docker 宣布原生支持 WebAssembly
java·运维·docker·容器·rust·wasm
chouchuang15 小时前
day-030-综合练习-笔记管理器
开发语言·笔记·python
Reart15 小时前
Leetcode 213.打家劫舍2(内含闲谈,打劫真是技术活,好题,716)
后端·算法