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

本文结束。

相关推荐
xyq20241 分钟前
SQLite 命令详解
开发语言
xinhuanjieyi6 分钟前
php setplayersjson实现类型转换和文件锁定机制应对高并发
android·开发语言·php
前端 贾公子20 分钟前
uniapp中@input修改input内容不生效 | 过滤赋值无效 | 连续非法字符不更新的问题
开发语言·前端·javascript
五阿哥永琪22 分钟前
从零读懂 Java 函数式接口:Function、Consumer、Supplier、Predicate
java·开发语言
蓝悦25 分钟前
用 .bat 一键启动 Jupyter:多环境切换
后端
写不来代码的草莓熊25 分钟前
el-date-picker ,自定义输入数字自动转换显示yyyy-mm-dd HH:mm:ss格式 【仅双日历 datetimerange专用】
开发语言·前端·javascript
何陋轩27 分钟前
Netty高性能网络编程深度解析:把网络框架核心讲透,让面试官刮目相看
后端·面试
落木萧萧82528 分钟前
为什么我又写了一个 ORM 框架(MyBatisGX)
后端·架构
I疯子32 分钟前
2026-04-13 打卡第 6 天
开发语言·python
断眉的派大星34 分钟前
值传递和引用传递
开发语言