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

本文结束。

相关推荐
兩尛5 小时前
c++知识点2
开发语言·c++
fengfuyao9855 小时前
海浪PM谱及波形的Matlab仿真实现
开发语言·matlab
xiaoye-duck5 小时前
C++ string 底层原理深度解析 + 模拟实现(下)——面试 / 开发都适用
开发语言·c++·stl
Hx_Ma166 小时前
SpringMVC框架提供的转发和重定向
java·开发语言·servlet
期待のcode7 小时前
原子操作类LongAdder
java·开发语言
lly2024068 小时前
C 语言中的结构体
开发语言
JAVA+C语言8 小时前
如何优化 Java 多主机通信的性能?
java·开发语言·php
青岑CTF9 小时前
攻防世界-Ics-05-胎教版wp
开发语言·安全·web安全·网络安全·php
Li emily9 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
APIshop10 小时前
Java 实战:调用 item_search_tmall 按关键词搜索天猫商品
java·开发语言·数据库