if / match
pub fn animal_habitat(animal: &str) -> &'static str {
let id = if animal == "crab" { //id等于(或拥有)了一个匿名函数的返回值
1
} else if animal == "gopher" {
2
} else if animal == "snake" {
3
} else {
-1
};
}
match number {
// 匹配单个值
1 => println!("One!"),
// 匹配多个值
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
// 匹配一个闭区间范围
13..=19 => println!("A teen"),
// else
_ => println!("Ain't special"),
}
for while loop
for n in 1..101 {}
for n in 1..=100 {}
for number in (1..101).rev() {}
for name in names.iter() {}
for name in names.into_iter() {}
for name in names.iter_mut() {}
'counting_up: loop {
loop {
if id == 1 {
break;
}
if id == 2 {
break 'counting_up;
}
}
slice array tuple
fn slice_out_of_array() {
let mut a :[i32] = [0; 100]; //100个0,[i32]表i32的数组
let a = [1, 2, 3, 4, 5]; //遮蔽shadow,变量另用
let nice_slice = &a[1..4];
//slice前面要加&
}
fn indexing_tuple() {
let numbers = (1, 2, 3);
let second = numbers.1; //成员
let (a,b,c)=numbers; //拆解tuple
}
vector
数组array的空间已知,分配到内存的栈Stack
部分;
向量vector空间未知,可以随意拓展/收缩空间,分配到堆Heap
。
fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // a plain array
let v = vec![10, 20, 30, 40]; //macro for vectors
(a, v)
}
标签:slice,..,python,c++,let,animal,println,array,rust
From: https://www.cnblogs.com/nolca/p/18040998