Rust Learning Day1

Learn Rust for the Future: Day 1

Reference: The Rust Programming Language

This book is the official tutorial for Rust.

Install Cargo

Cargo is Rust's package manager, similar to Maven in Java. You can use it to create and manage projects. For example, to create a new project named guessing_game, you can run:

sh 复制代码
cargo new guessing_game

The Cargo.toml file is like pom.xml in Maven. It manages your project's dependencies. In this case, there is only one dependency named rand, which is used to generate random numbers. The line rand = "0.8.5" is shorthand for rand = "^0.8.5", meaning it will use versions from 0.8.5 up to, but not including, 0.9.0. If a new compatible version, like 0.8.6, is released, you can update to it using cargo update. However, if the new version has incompatible changes, it might break your program. Therefore, Cargo.lock is required to ensure consistent versions.

Here's an example Cargo.toml file for the guessing game project:

toml 复制代码
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8.5"

The Cargo.lock file is generated automatically by Cargo and keeps track of the exact versions of all dependencies.

Features Compared to Java

In Rust, you can declare variables as immutable by default using let, which means you cannot change their value later:

rust 复制代码
let x = 1;
// error: x is immutable
x = 2;

To make a variable mutable, use mut:

rust 复制代码
let mut x = 2;
x = 3;

Rust also supports variable shadowing, allowing you to declare a variable with the same name in a different scope. This feature allows the variable to have different types or values in different scopes:

rust 复制代码
let x = 3;
{
    let x = 12;
    // x: 12 within this scope
    println!("x: {x}");
}
// x: 3 outside the inner scope
println!("x: {x}");

Shadowing allows you to transform a variable's type, while mut does not. When the scope ends, the variable reverts to its original value.

相关推荐
赏金术士27 分钟前
Kotlin 从入门到进阶 之作用域函数 & 优雅写法(五)
android·开发语言·kotlin
数据小馒头28 分钟前
SQL与数据库开发(三):MySQL 原生 JSON 操作实战
后端
openKaka_38 分钟前
从 scheduleUpdateOnFiber 到 Root 微任务调度:React 如何把更新交给调度系统
开发语言·前端·javascript
盏灯1 小时前
以前有一个同事说:最讨厌下班提需求又没电脑在身边...
前端·后端·面试
人道领域1 小时前
【黑马点评日记】:用户签到功能详解——从Bitmap入门到避坑指南
java·数据库·redis·后端
梦梦代码精1 小时前
《企业开源商城选型:商业闭环、二次开发与成本平衡》
java·开发语言·低代码·开源·github
前进的李工1 小时前
智能Agent实战指南:记忆组件嵌入技巧(记忆)
开发语言·前端·javascript·python·langchain·agent
测试员周周1 小时前
【AI测试功能5】AI功能测试的“黄金数据集“构建指南:从0到1搭建质量评估体系
运维·服务器·开发语言·人工智能·python·功能测试·集成测试
蓝眸少年CY1 小时前
Scala - 基础教程
开发语言·后端·scala
Kiyra1 小时前
从上传到可问答:Interview Agent 的知识库 RAG 链路
java·人工智能·后端·spring·职场和发展