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

本文结束。

相关推荐
码事漫谈2 小时前
当公司不久后变成冒险者公会,我担心什么
后端
星落梦生2 小时前
SpringAOP基础笔记(7)
java·开发语言
Csvn3 小时前
Nginx 负载均衡进阶与健康检查:哈希、keepalive 池与 DNS 自愈
后端·nginx
皮皮林5514 小时前
京东又开源一款新框架,用起来真优雅!
后端
学长毕设4 小时前
基于SpringBoot智慧养老服务平台设计与实现-附源码
java·spring boot·后端
曹牧4 小时前
Java:“刷新雪崩”
java·开发语言
郝学胜-神的一滴4 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus5 小时前
C++ explicit 关键字工程实践
开发语言·c++
郝学胜-神的一滴7 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
行百里er7 小时前
【Spring Insight 技术分享】跨服务调用链路是怎么串起来的?
后端·spring·开源