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.

相关推荐
froginwe114 分钟前
Maven 仓库概述
开发语言
1***t82714 分钟前
将 vue3 项目打包后部署在 springboot 项目运行
java·spring boot·后端
疯狂的程序猴27 分钟前
iOS 日志管理的工程化实践 构建从开发调试到系统日志分析的多工具协同体系
后端
申阳34 分钟前
Day 17:03. 基于 Tauri 2.0 开发后台管理系统-登录页面开发
前端·后端·程序员
二川bro37 分钟前
Python在AI领域应用全景:2025趋势与案例
开发语言·人工智能·python
疯狂的程序猴1 小时前
Transporter 在 iOS 上架流程中的角色变化 本地上传工具的定位、局限与多工具协作趋势分析
后端
N***H4861 小时前
使用Springboot实现MQTT通信
java·spring boot·后端
CoderYanger1 小时前
优选算法-队列+宽搜(BFS):72.二叉树的最大宽度
java·开发语言·算法·leetcode·职场和发展·宽度优先·1024程序员节
白气急1 小时前
别用“设计感”掩盖无知:从一次 null == 0 的事故说起
后端
疏狂难除1 小时前
随便玩玩lldb (二)
开发语言·后端·rust