变量常量
let x = "你好世界";
let mut x;
x = 1;
const Y: bool = true & false;
{
let x = x;
}
x = 3;
数据类型
标量
let x: i128 = 98_222;
let x: u128 = 0xff;
let x: isize = 0o77;
let x: usize = 0b1111_0000;
let x: u8 = b'A';
let x: f64 = 2.0;
let y: f32 = 3.0;
let t = true;
let f: bool = false;
let c = 'z';
let z = 'ℤ';
let heart_eyed_cat: char = '😻';
矢量
let tup: (i32, f64, u8) = (500, 6.4, 1);
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
let five_hundred = x.0;
let a: [i32; 5] = [1, 2, 3, 4, 5];
let a = [3; 5];
let first = a[0];
函数
fn main() {
let x = plus_one(5);
println!("The value of x is: {}", x);
}
fn plus_one(x: i32) -> i32 {
x + 1
}
控制结构
let number = 3;
if number < 5 {
println!("condition was true");
} else if number < 8 {
println!("condition was false");
} else {
}
let condition = true;
let number = if condition { 5 } else { 6 };
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
}
for number in (1..4).rev() {
println!("{}!", number);
}
所有权
String
let s = String::from("hello");
let mut s = String::from("hello");
s.push_str(", world!");
所有权
let x = 5;
let y = x;
let s1 = String::from("hello");
let s2 = s1;
let s3 = s2.clone();
引用与借用
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
let mut s1 = String::from("hello");
change(&mut s1);
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn change(some_string: &mut String) {
some_string.push_str(", world");
}
- 常引用可以有多个 但可变引用只能有1个
- 常引用与可变引用不能同时存在
let mut s = String::from("hello");
{
let r1 = &mut s;
}
let r2 = &mut s;
let mut s = String::from("hello");
let r1 = &s;
println!("{} and {}", r1, r2);
let r3 = &mut s;
悬垂指针
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}