Skip to content

Commit 81185e7

Browse files
author
zhangdong
committed
rust 数据类型
1 parent 2781058 commit 81185e7

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

rust/types.md

+34
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,41 @@ String不是Char的数组,不能使用下标进行访问
439439
## 向量类型
440440

441441
- **`Vec<f64>`**: 向量,可变长度,其元素类型为 `f64`
442+
```rust
443+
let v: Vec<i32> = Vec::new();//这里是空的所以需要手动指定类型
444+
let v = vec![1, 2, 3];//如果有数值可以直接使用宏
445+
```
446+
填充-push
447+
读取-通过索引或使用get方法
448+
```rust
449+
let v = vec![1, 2, 3, 4, 5];
450+
451+
let third: &i32 = &v[2];
452+
println!("The third element is {third}");
453+
454+
let third: Option<&i32> = v.get(2);
455+
match third {
456+
Some(third) => println!("The third element is {third}"),
457+
None => println!("There is no third element."),
458+
}
459+
```
460+
迭代,必须要借用,否则所有权会丢失
461+
462+
```rust
463+
let v = vec![100, 32, 57];
464+
for n_ref in &v {
465+
// n_ref has type &i32
466+
let n_plus_one: i32 = *n_ref + 1;
467+
println!("{n_plus_one}");
468+
}
442469

470+
//需要修改原来的向量
471+
let mut v = vec![100, 32, 57];
472+
for n_ref in &mut v {
473+
// n_ref has type &mut i32
474+
*n_ref += 50;
475+
}
476+
```
443477
## 切片类型
444478

445479
- **&[u8]**: 对切片(数组或向量某一部分)的引用,类型为 `u8`

0 commit comments

Comments
 (0)