Vector可变数组长度集合
vector: 可变数组长度存储一系列相同类型的值, vector值在内存中是连续存放,如果没有足够内存空间分配新内存并且将老内存copy,不断增加会导致vector 第一个元素引用会释放重新分配
fn main() {
// 两种方式创建vector let v = vec![1,2,3]通过宏定义并且初始化
let mut v = Vec::new(); // 更新vector 值 必须使用mut 关键字
v.push(5);
v.push(6);
v.push(7);
let third: &i32 = &v[2];
match v.get(2) {
Some(third) => println!("the value is {}", third),
None => println!("There is no third element."),
}
}
- 不能在get时候同时进行put
当 vecto结尾增加新元素时候,在没有足够的空间将所有元素依次向量存放时候,可以要求分配新内存将老内存拷贝到新空间,导致第一个元素的引用指向被释放了
let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0];
v.push(6);
println!("The first element is: {}", first);
$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:6:5
|
4 | let first = &v[0];
| - immutable borrow occurs here
5 |
6 | v.push(6);
| ^^^^^^^^^ mutable borrow occurs here
7 |
8 | println!("The first element is: {}", first);
| ----- immutable borrow later used here
rust 中字符串
- rust倾向暴露出更可能的错误,字符串比很多程序员想像根据复杂结构,rust中字符串作为字节结合和其不同其他集合的索引
- UTF-8 编码
rust核心语言中只有一种字符串类型 str(基础类型), slice 通常是以被借用形式出现
String 是rust 标准库提供的 是可增长,可变的,有所有权的UTF-8编码的字符串类型,类似于Java Class类
let mut s = String::new();
或者to_string()初始化
let s = String::from("inital contens");
等价于
let data = "initial conetnt".to_string();
- 使用 put_str, + ,format! 宏进行增加长度
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2);
println!("s2 is {}", s2);
- 索引字符串
fn main() {
let s1 = String::from("hello");
let h = s1[0];
}
| let h = s1[0];
| ^^^^^ `String` cannot be indexed by `{integer}`
|
= help: the trait `Index<{integer}>` is not implemented for `String`
为什么rust不支持索引????
- String内部封装Vec(u8), 内部使用UTF-8进行表面,在对于表达相同意思您好,但是使用不同的语言字符串比如梵语和中文时候,UTF-8 编码所占的字节不一样的,导致字节索引并不能对于一个有效的Unicode标量值
- rust提供多种不同方式解释计算机存储原始字符串的数据,无所谓的人类语言
- rust不允许使用索引获取String字符串原因,索引操作总是需要常数时间,但是String不可能保证这样性能,
rust必须从开头到索引位置遍历0(N)确定有效的字符串
- 如果想要索引创建切片时候 使用如下
let hello = "Здравствуйте";
let s = &hello[0..4]; //如果使用[0..1]l类似索引会让程序崩溃
- 总结字符串是非常复杂, 主要原因不同的语言选择了不同的相程序员展示其复杂性方式,Rust 选择了以准确的方式处理 String 数据作为所有 Rust 程序的默认行为,这意味着程序员们必须更多的思考如何预先处理 UTF-8 数据。
hashMap
fn main() {
use std::collections::HashMap;
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let mut scores: HashMap<_, _> =
teams.into_iter().zip(initial_scores.into_iter()).collect();
}
--- 覆盖一个值
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
println!("{:?}", scores);
-- 没有key插入