Vec
1.vector由标准库提供
2.可以储存多个值
3.只能存储相同类型的数据
4.值在内存中连续存放
创建vector
Vec::new 函数
fn main(){
let vec1:Vec = Vec::new();//方法一
let vec2 = vec![1, 2, 3];//方法二 宏
println!("{}", vec2[0]);
}
更新vector: push
fn main(){
//let v = vec![1, 2, 3];
let mut v = Vec::new();//创建空vector
v.push(1);
for i in v{
println!("{}", i);
}
}
fn main(){
let mut v = vec![1, 2, 3];
v.push(42);
println!("{}", v[3]);//42
}
fn main(){
let mut v = vec![1, 2, 3];
for i in &mut v{
*i += 50;
println!("{}", i);//51 52 53
}
for i in v{
println!("{}", i);//51 52 53
}
}
为了使vector能存放不同数据类型可以配合enum使用
String::new() —— 创建空String类型变量
a.to_string() —— 将字符串切片、字符串字面值转换成String类型
String::from() —— 创建String类型
push_str() —— 把一个字符串切片附加到String
fn main(){
let mut str = String::from("ws");
str.push_str("xzc");
println!("{}", str);//wsxzc
}
push() —— 把单个字符附加到String
+:连接字符串
format!() —— 拼接字符串
fn main(){
let str1 = String::from("ws");
let str2 = String::from("xzc");
let s = format!("{}-{}", str1, str2);
println!("{}", s);
}
fn main(){
let s = String::from("xzc");
for i in s.chars(){
println!("{}", i);//x z c
}
for i in s.bytes(){
println!("{}", i);//120 122 99
}
}
切割String
fn main(){
let s = String::from("xzc");
let S = "what";
let s_cut = &s[..2];
let S_cut = &S[..3];
println!("{}", s_cut);//xz
println!("{}", S_cut);//wha
}
一个键(Key)对应一个值(Value)
Hash函数:决定如何在内存中存放K和V
let mut scores:HashMap = HashMap::new();//创建空hashmap
use std::collections::HashMap;
fn main(){
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);//insert()给空hashmap赋值
scores.insert(String::from("Yellow"), 50);
}
同构的,在hashmap中
所有的K必须是同一种类型
所有的V必须是同一种类型
访问hashmap中的值
use std::collections::HashMap;
fn main(){
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);//insert()给空hashmap赋值
scores.insert(String::from("Yellow"), 50);
println!("{}, {}", scores["Blue"], scores["Yellow"]);
}
use std::collections::HashMap;
fn main(){
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);//insert()给空hashmap赋值
scores.insert(String::from("Yellow"), 50);
//println!("{}, {}", scores["Blue"], scores["Yellow"]);
for (k, v) in &scores{
println!("{}, {}", k, v);
}
}
更新hashmap
1.要添加的(k, v)中的k值,在原hashmap中存在,则新v替换旧v
use std::collections::HashMap;
fn main(){
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);//insert()给空hashmap赋值
scores.insert(String::from("Yellow"), 50);
scores.insert(String::from("Yellow"), 100);
println!("{:#?}", scores);//Yellow, 100 Blue, 10
}
2.若k值在原hashmap中不存在,则直接添加(k, v)键值对