文章目录
一、让程序跑起来
使用cargo创建一个项目,输出hello,world!
$cargo new hello
# hello.rs
fn main() {
println!("Hello, world!");
}
------------------
$cargo run hello
Compiling hello v0.1.0 (D:\RustPro\hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.39s
Running `target\debug\hello.exe hello`
Hello, world!
二、常量和变量
rust语言和其他语言一样,也分常量和变量
- 常亮就是一直不变的,程序中不可以更改,使用const 进行定义
- 变量就是可变量,在Rust中分为可变变量和不可变变量
- 不可变变量使用 let 进行定义
-可变变量使用 let mut 进行定义
1.常量
# 正确使用
fn main() {
const MAX_POINTS: u32 = 100_000;
println!("{}",MAX_POINTS);
}
输出:100000
# 错误使用,在程序中修改常量
fn main() {
const MAX_POINTS: u32 = 100_000;
MAX_POINTS = 200_000;
println!("{}",MAX_POINTS);
}
$cargo run hello
Compiling hello v0.1.0 (D:\RustPro\hello)
error[E0070]: invalid left-hand side of assignment
--> src\main.rs:3:16
|
3 | MAX_POINTS = 200_000;
| ---------- ^
| |
| cannot assign to this expression
For more information about this error, try `rustc --explain E0070`.
error: could not compile `hello` (bin "hello") due to previous error
2.变量
# 不可变变量在程序中无法修改
fn main() {
let mut x:i64 = 6;