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.

相关推荐
aq55356001 分钟前
数字资源分发的技术革命与未来趋势
java·开发语言·python·php
AI玫瑰助手3 分钟前
Python基础:元组的定义与不可变特性(对比列表)
开发语言·python·信息可视化
张驰咨询公司6 分钟前
六西格玛数据分析实战:用Python实现DPMO与西格玛水平计算
开发语言·python·数据分析·六西格玛培训·六西格玛培训公司
invicinble11 分钟前
对于java基础
java·开发语言
逻辑驱动的ken21 分钟前
Java高频面试考点场景题13
java·开发语言·jvm·面试·求职招聘·春招
Evand J22 分钟前
【MATLAB代码介绍】无迹粒子滤波(Unscented Particle Filter),运动目标滤波定位
开发语言·matlab·粒子滤波·upf·无迹
bubiyoushang88826 分钟前
MATLAB考虑源荷不确定性的电力系统优化
开发语言·matlab
lclcooky29 分钟前
Spring Boot 整合 Keycloak
java·spring boot·后端
Ares-Wang41 分钟前
Flask》》flask-login
后端·python·flask
自信150413057591 小时前
重生之从0开始学习c++之string(上)
开发语言·c++·学习