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.

相关推荐
A_aspectJ3 分钟前
Java开发的学习优势:稳定基石与多元可能并存的技术赛道
java·开发语言
qq_283720055 分钟前
Python 模块精讲:collections —— 高级数据结构深度解析(defaultdict、Counter、deque)
java·开发语言
wjs202417 分钟前
Chart.js 饼图指南
开发语言
YSF2017_321 分钟前
C语言-12-静态库制作
c语言·开发语言
青槿吖28 分钟前
第二篇:从复制粘贴到自定义规则!Spring Cloud Gateway 断言 + 过滤全玩法,拿捏微服务流量管控
java·spring boot·后端·spring cloud·微服务·云原生·架构
SamDeepThinking33 分钟前
C端多渠道用户体系设计:从需求到落地
java·后端·架构
圆山猫1 小时前
[AI] [Linux] 教我编一个启用rust的riscv kernel用于qemu启动
linux·ai·rust
凤凰院凶涛QAQ1 小时前
《C++转JAVA快速入手系列》:基本通用语法篇
java·开发语言·c++
zjun10011 小时前
QT:语言翻译
开发语言·qt
Shadow(⊙o⊙)1 小时前
C++常见错误解析2.0
开发语言·数据结构·c++·后端·学习·算法