Rust 编程视频教程对应讲解内容-vector
视频地址
头条地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
网易云课堂地址:https://study.163.com/course/introduction....
讲解内容
1、新建vector
(1)新建空的vector
let v: Vec<i32> = vec::new();
(2)新建包含初始值的vector
let v = vec![1, 2, 3];
2、更新vector
let mut v = Vec::new();
v.push(5);
v.push(6);
3、丢弃vector时也丢弃其所有元素
{
let v = vec![1, 2, 3];
...
//此处离开v的作用域,v被丢弃,其中的元素也被丢弃
}
4、读取vector元素
let v = vec![1, 2, 3, 4, 5];
//方法一:使用索引
let third: &i32 = &v[2]; //third = 3
//方法二:使用get方法,rust推荐的方法
match v.get(2) {
Some(value) => println!("value = {}", value),
None => println!("None"),
}
//----复习知识点:不能在相同作用域下同时使用可变和不可变引用----
let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0]; //不可变引用
v.push(6);
println!("first = {}", first); //error,因为上一行已经变化(可变引用)
4、遍历vector
(1)不可变方式
let v = vec![1, 2, 3];
for i in &v {
println!("{}", i);
}
(2)可变方式
let v = vec![1, 2, 3];
for i in &mut v {
*i += 1;
println!("i+1 = {}", i);
}
5、使用枚举存储多种类型
enum Content {
Text(String),
Float(f64),
Int(i32),
}
let c = vec![
Content::Text(""String::),
Content::Int(-2),
Content::Float(0.99)
];
本作品采用《CC 协议》,转载必须注明作者和本文链接