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.

相关推荐
2601_966949651 小时前
如何根据研究的起止时间截取分钟级行情?Python 实战与 QuantDash 数据处理指南
开发语言·python·pandas·量化交易·1024程序员节·股票数据·quantdash
晨曦中的暮雨3 小时前
限流算法——固定窗口、滑动窗口、漏桶、令牌桶
java·开发语言·算法
喵了几个咪4 小时前
GoWind CMS 拆解:在 Go 里给 TipTap 搭一套 Yjs 协同后端
开发语言·后端·golang
Flynt4 小时前
我把微信运动的排行榜和定点推送复刻了一遍:100万次步数更新只要4秒,坑在别处
redis·后端·性能优化
程序员清风4 小时前
数据处理脚本工程化:日志、配置、命令行与测试
服务器·开发语言·数据库
2601_962885726 小时前
如何用 Python 把 K 线重采样成任意周期?
开发语言·python
_孤傲_6 小时前
快速掌握 MySQL 语法
数据库·后端·mysql
Wang's Blog6 小时前
Java 项目实战: 交友项目 - 圈子功能实现:总结
java·开发语言·交友
下一站春风里7 小时前
位运算完整学习笔记:按位与(&)+ 异或(^)
开发语言·c++·算法
IT_陈寒8 小时前
Java静态变量初始化坑得我头皮发麻
前端·人工智能·后端