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

本文结束。

相关推荐
leaves falling20 分钟前
C语言内存函数-
c语言·开发语言
至为芯2 小时前
IP6537至为芯支持双C口快充输出的45W降压SOC芯片
c语言·开发语言
小羊羊Python2 小时前
SoundMaze v1.0.1正式发布!
开发语言·c++
浩瀚地学2 小时前
【Java】JDK8的一些新特性
java·开发语言·经验分享·笔记·学习
l1t2 小时前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
XXOOXRT3 小时前
基于SpringBoot的加法计算器
java·spring boot·后端·html5
yugi9878384 小时前
基于遗传算法优化主动悬架模糊控制的Matlab实现
开发语言·matlab
moxiaoran57534 小时前
Go语言的错误处理
开发语言·后端·golang
yugi9878385 小时前
MATLAB的多层感知器(MLP)与极限学习机(ELM)实现
开发语言·matlab
Never_Satisfied5 小时前
C#获取汉字拼音字母方法总结
开发语言·c#