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.

相关推荐
码事漫谈3 小时前
AI正在攻破你的密码
后端
皮皮林5514 小时前
一款开源强大的数据同步神器,主流数据库全支持!
后端
FRing034 小时前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2
wefg14 小时前
【项目】C++ 基于 Vibe Coding 的 OJ 平台
开发语言·c++
喵个咪5 小时前
GoWind Trade(风帆):从询盘到收款的外贸全流程一体化平台
后端·架构·go
喵个咪5 小时前
GoWind Ops:开箱即用的多节点运维平台——管机器、跑项目、发脚本、构建分发
后端·go·自动化运维
喵个咪6 小时前
GoWind IM 私有化快速部署:研发型企业自己的协同底座
后端·架构·go
喵个咪6 小时前
GoWind IoT(风行物联网):从设备接入到告警运维的设备管理平台
后端·物联网·go
我叫黑大帅6 小时前
换尺寸、转个角度就认不出同一张图?让 16×16 灰度网格做感知去重
后端·面试·php
JavaGuide7 小时前
刚刚,GLM-5.4 正式发布,实测来了:看图用 Blender 建凉亭、做技术视频,再画一辆真能传动的自行车
前端·后端