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

本文结束。

相关推荐
CHANG_THE_WORLD21 小时前
PDFium导出pdf 图像
开发语言·c++·pdf
owCode21 小时前
4-C++智能指针
开发语言·c++
liu****21 小时前
10.queue的模拟实现
开发语言·数据结构·c++·算法
阑梦清川21 小时前
docker部署tomcat和nginx
后端
哦你看看21 小时前
学习Python 03
开发语言·windows·python
程序员码歌1 天前
豆包Seedream4.0深度体验:p图美化与文生图创作
android·前端·后端
小龙报1 天前
《彻底理解C语言指针全攻略(6)-- qsort、sizeof和strlen》
c语言·开发语言·职场和发展·创业创新·学习方法·业界资讯·visual studio
郝学胜-神的一滴1 天前
Three.js光照技术详解:为3D场景注入灵魂
开发语言·前端·javascript·3d·web3·webgl
fie88891 天前
基于Matlab的深度堆叠自编码器(SAE)实现与分类应用
开发语言·分类
_w_z_j_1 天前
C++11----列表初始化和initializer_list
开发语言·c++