RUST学习-集合

vec

类似于java类型的List和golang的切片

创建方法

俩种方法一种是Vec::new,一种是vec!宏

1
2
let v: Vec<i32> = Vec::new();
let mut v = vec![1, 2, 3, 4];

更新

vec.push(v);

get

索引访问和match访问,索引访问会出现数组越界的painc,而match返回值是Option,因为有None的存在所以不会出现数组月觉的patinc

1
2
3
4
5
6
7
8
9
10
11
println!("out of index 100 {}",v[100]);//panicked at 'index out of bounds: the len is 4 but the index is 100'


match v.get(2) {
Some(v)=>{println!("v.get this element is {}",v)},
None=>{println!("v.get out of index")}
}
match v.get(100) {
Some(v)=>{println!("v.get this element is {}",v)},
None=>{println!("v.get out of index")}
}

遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
//遍历vector,第一次遍历用可变应用可以修改里面的值
let mut v1=vec![100,50,2];
for i in &mut v1{
*i=*i+40;
}

for i in &v1{
println!("{}",i)
}

for (index,i) in v1.iter().enumerate(){
println!("index {} v {}", index,i);
}

String

rust在处理字符串时候常用&str和String俩种类型,其中&str是字符串字面值,String是标准库提供的

常用函数/宏

  • String::from将str构造成String
  • format!通过占位符”{}”,格式化
  • String实际上是char类型的数组,所以可以采用切片方式访问即:&s4[0..4],
1
2
3
4
5
6
7
8
9
10
11
let s="hello";//这是&str类型
let s1=String::from("Hello");//这是string
let s2=String::from(" World!");
let s4=format!("{}{}",s1,s2);
println!("{}",s4);

println!("{}",&s4[0..4]);//

for c in s4.chars(){
println!("{}",c);
}

HashMap

创建方法

1
2
3
4
let mut hash_map = HashMap::new();

//拉链方法,需要显示制定类型
let hash_map: HashMap<_, _> = keys.iter().zip(values).collect();

更新

insert

1
2
3
4
hash_map.insert("blue", 1);

//entry可以做到没有在插入
hash_map.entry(String::from("yellow")).or_insert(50);

get

get

1
2
3
4
match hash_map.get("yellow") {
Some(v) => println!("match Some {}", v),
None => println!("key empty"),
}

遍历

1
2
3
for (k,v) in hash_map{
println!("{},{}",k,v);
}