Rust入门教程:变量到数据类型,轻松掌握!想学一门既强大又安全的编程语言?Rust绝对值得一试!这篇教程专为初学者打造,带你轻松掌握Rust的核心基础——从变量的声明与可变性,到数据类型和复合类型的应用。代码示例简单直观,零基础也能快速上手!快来一起探索Rust的魅力,开启你的系统编
想学一门既强大又安全的编程语言?Rust 绝对值得一试!这篇教程专为初学者打造,带你轻松掌握 Rust 的核心基础——从变量的声明与可变性,到数据类型和复合类型的应用。代码示例简单直观,零基础也能快速上手!快来一起探索 Rust 的魅力,开启你的系统编程新旅程!
这篇 Rust 入门教程让你快速掌握编程基础!通过通俗的讲解和实用代码示例,带你学会变量与可变性、标量类型(整数、浮点数等)以及元组和数组的使用。无需复杂背景,轻松搞定 Rust 核心技能,适合所有编程新手!
let
关键字mut
,就可以使变量可变。~/rust
➜ cargo new variables
Created binary (application) `variables` package
~/rust
➜ cd var*
variables on master [?] via 🦀 1.67.1
➜ code .
variables on master [?] via 🦀 1.67.1
➜
fn main() {
println!("Hello, world!");
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
mut
,常量永远都是不可变的const
关键字,它的类型必须被标注MAX_POINTS
const MAX_POINTS: u32 = 100_000;
// const MAX_POINTS: u32 = 100_000;
fn main() {
// const MAX_POINTS: u32 = 100_000;
println!("Hello, world!");
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
let x = x + 1;
let x = x * 2;
println!("The value of x is {}", x);
let spaces = " ";
let spaces = spaces.len();
println!("The length of spaces is {}", spaces);
let guess: u32 = "42".parse().expect("Not a number");
println!("The guess is {}", guess);
}
length | signed | unsigned |
---|---|---|
8-bit | i8 | u8 |
16-bit | i16 | u16 |
32-bit | i32 | u32 |
64-bit | i64 | u64 |
128-bit | i128 | u128 |
arch | isize | usize |
十进制、十六进制、八进制、二进制、byte
// const MAX_POINTS: u32 = 100_000;
fn main() {
// const MAX_POINTS: u32 = 100_000;
println!("Hello, world!");
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
let x = x + 1;
let x = x * 2;
println!("The value of x is {}", x);
let spaces = " ";
let spaces = spaces.len();
println!("The length of spaces is {}", spaces);
let guess: u32 = "42".parse().expect("Not a number");
println!("The guess is {}", guess);
// let x = 2.0; // f64
// let y: f32 = 3.0; // f32
// let sum = 5 + 10;
// let difference = 95.5 - 4.3;
// let product = 4 * 30;
// let quotient = 56.7 / 32.2;
// let reminder = 54 % 5;
// let t = true;
// let f: bool = false;
// let x = 'z';
// let y: char = 'a';
// let z = '😘';
}
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
println!("{}, {}, {}", tup.0, tup.1, tup.2);
let (x, y, z) = tup;
println!("{}, {}, {}", x, y, z);
}
let a: [i32; 5] = [1, 2, 3, 4, 5];
let a = [3; 5];
它就相当于:let a = [3, 3, 3, 3, 3];
fn main() {
// let a = [1, 2, 3, 4, 5];
let months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
// let first = months[0];
// let second = months[1];
// let index = 15;
let index = [12, 13, 14, 15];
let month = months[index[1]];
println!("{}", month);
}
恭喜你迈出 Rust 编程的第一步!通过这篇教程,你已经轻松掌握了变量、数据类型和复合类型的基础知识,这些是构建 Rust 程序的基石。现在就打开编辑器,试着写几行 Rust 代码,感受它的强大吧!想更深入?关注我们的 Rust 教程系列,下一站带你探索更多精彩内容!
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!