当前位置: 首页 > article >正文

从零开始学 Rust:安装与 Hello World

两年没有更新博客啦!走上了搬砖的道路,也如愿以偿选择了自己认准的方向,还遇到了超帅超牛的导师。因为项目需要,决定跟的这个教程系统学习一下Rust。

近期决定把这个系列翻新重写一次,希望能和大家一起入门Rust。至于我整理这个系列笔记的动机,可以参见《我为什么要学习 Rust?》。

我跟的第一个教程被称为The Book,是一本比较容易跟做的入门指南。

文章目录

  • 简介
  • 安装
  • Hello, World!
  • Hello, Cargo!
  • 自学案例:设计猜数字游戏

简介

  • … the Rust programming language is fundamentally about empowerment: no matter what kind of code you are writing now, Rust empowers you to reach farther, to program with confidence in a wider variety of domains than you did before.
  • High-level ergonomics and low-level control are often at odds in programming language design; Rust challenges that conflict.

安装

我用的环境是 VSCode 的 WSL,使用 Ubuntu 系统。

Linux/MacOS:

curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
sudo apt install build-essential

配置文件:

source $HOME/.cargo/env

检查安装情况

rustc --version
echo $PATH

我的是rustc 1.84.1 (e71f9a9a9 2025-01-27),岁月是把杀猪刀!

Hello, World!

fn main() {
    println!("Hello, world!");
}
rustc main.rs
./main
  • 四个空格缩进,println! 是Rust宏。
  • Compiling and Running Are Separate Steps
  • ahead-of-time compiled language
  • “rustacean”

Hello, Cargo!

[package]
name = "hello_cargo"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]
edition = "2018"

[dependencies]

Cargo 的配置文件格式 TOML (Tom’s Obvious, Minimal Language)

cargo build
cargo run
cargo check
  • We can build a project using cargo build or cargo check.

  • We can build and run a project in one step using cargo run.

  • Instead of saving the result of the build in the same directory as our code, Cargo stores it in the target/debug directory.

  • Building for Release: cargo build --release

  • Cargo as convention: The Cargo Book

自学案例:设计猜数字游戏

这部分的内容我保留了英文原文,大家耐心阅读,会有很深入的理解。

use std::io;

fn main() {
    println!("Guess the 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);
}

This is a let statement, which is used to create a variable.

let foo = 5; // immutable
let mut bar = 5; // mutable

The :: syntax in the ::new line indicates that new is an associated function of the String type. An associated function is implemented on a type, in this case String, rather than on a particular instance of a String. Some languages call this a static method.

The & indicates that this argument is a reference, which gives you a way to let multiple parts of your code access one piece of data without needing to copy that data into memory multiple times. Like variables, references are immutable by default. Hence, you need to write &mut guess rather than &guess to make it mutable.

read_line puts what the user types into the string we’re passing it, but it also returns a value—in this case, an io::Result. Rust has a number of types named Result in its standard library: a generic Result as well as specific versions for submodules, such as io::Result.

For Result, the variants are Ok or Err. The Ok variant indicates the operation was successful, and inside Ok is the successfully generated value. The Err variant means the operation failed, and Err contains information about how or why the operation failed.

The purpose of these Result types is to encode error-handling information. Values of the Result type, like values of any type, have methods defined on them. An instance of io::Result has an expect method that you can call. If this instance of io::Result is an Err value, expect will cause the program to crash and display the message that you passed as an argument to expect. If the read_line method returns an Err, it would likely be the result of an error coming from the underlying operating system. If this instance of io::Result is an Ok value, expect will take the return value that Ok is holding and return just that value to you so you can use it. In this case, that value is the number of bytes in what the user entered into standard input.

SemVer

When you build a project for the first time, Cargo figures out all the versions of the dependencies that fit the criteria and then writes them to the Cargo.lock file. When you build your project in the future, Cargo will see that the Cargo.lock file exists and use the versions specified there rather than doing all the work of figuring out versions again. This lets you have a reproducible build automatically.

  • Rust has a strong, static type system. [强静态类型系统]

程序清单:

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1, 101);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}

http://www.kler.cn/a/559459.html

相关文章:

  • Rocky8 源码安装 HAProxy
  • 基于Spring Boot的党员学习交流平台设计与实现(LW+源码+讲解)
  • AI回答:Linux C/C++编程学习路线
  • Docker 容器操作笔记
  • Office和WPS中使用deepseek,解决出错问题,生成速度极快,一站式AI处理文档
  • 基于ffmpeg+openGL ES实现的视频编辑工具-添加贴纸(八)
  • 企业组网IP规划与先关协议分析
  • HTML中,title和h1标签的区别是什么?
  • ip归属地和手机卡有关系吗?详细探析
  • 《Real-IAD: 用于基准测试多功能工业异常检测的真实世界多视角数据集》学习笔记
  • HTML/CSS中子代选择器
  • 写大论文的word版本格式整理,实现自动生成目录、参考文献序号、公式序号、图表序号
  • ElasticSearch+Kibana通过Docker部署到Linux服务器中
  • 游戏设计模式阅读 - 游戏循环
  • linux下软件安装、查找、卸载
  • ROS2 中 TF 变换发布与订阅:实现 base_link 和 test_link 实时可视化显示
  • Elasticsearch Open Inference API 增加了对 Jina AI 嵌入和 Rerank 模型的支持
  • Matplotlib,Streamlit,Django大致介绍
  • UniApp SelectorQuery 讲解
  • php重写上传图片成jpg图片