[rust整理笔记]rust基本语法之通用集合-03

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BaiHuaXiu123/article/details/88089137

这里主要介绍4种集合类型:

1. 数组
2. 动态数组vector
3. 字符串
4. 哈希map

1 数组
1.1 数组的定义

//    1)直接定义
    let arr = [1,2,3];
    println!("{:?}",arr);//[1,2,3]
//    2)指定大小
    let arr1:[i32;5] = [1,2,3,4,5];
    println!("{:?}",arr1);//[1,2,3,4,5]
//    3) 定义可变数组
    let mut arr2 = [1,2,3,4,5];
    arr2[0] = 100;
    println!("{:?}",arr2);//[100,2,3,4,5]
    4) 定义初始化
     let bb = [100;5];
    println!("{:?}",bb);//[100,100,100,100,100]

1.2 数组的访问

    // 1)数组访问
    let arr3 = [100,4,5,6,6];
    println!("{}",arr3[3]);
    // 2) 数组的遍历
    for item in arr3.iter() {
        println!("{}",item);
    }
   //    3) 数组切片
    let arr5 = [100,4,5,6,6];
    let arr4 = &arr5[0..3];
    println!("{:?}",arr4);

1.3 数组的方法

let array = [1,3,4,4,5,5,6,6];
let len = array.len();
println!("{}",len);

2 动态数组vector
2.1 vector定义

    // 1) new 关键字创建
    let mut v = Vec::new();
    v.push(5);
    // 2) 直接创建
    let mut  vec = vec![1,3,3,4];
    vec.push(23);
   // 3)读取
    let v = vec![1, 2, 3, 4, 5];
    let third: &i32 = &v[2];
    println!("The third element is {}", third);
    match v.get(2) {
        Some(third) => println!("The third element is {}", third),
        None => println!("There is no third element."),
    }
//    4) 定长vec遍历
    let v = vec![100, 32, 57];
    for i in &v {
        println!("{}", i);
    }
//    5) 可变vec遍历
    let mut v = vec![100, 32, 57];
    for i in &mut v {
        *i += 50;
        println!("{}",i);
    }

3 字符串
Rust 的核心语言中事实上就只有一种字符串类型:str,字符串 slice,它通常以被借用的形式出现,&str。

字符串常量
const LANGUAGE: &'static str = "Rust";
字符串字面值
let language = "Rust";
// 转换到一个字符串
let s = language.to_string();

字符串类型
String 类型是由标准库提供的,它是可增长的、可变的、有所有权的、UTF-8 编码的字符串类型。

let language = String::from("Rust");
遍历字符串
for c in "hello,world".chars() {
    println!("{}", c);
}
字符串 slice
使用 [] 和一个 range 来创建包含特定字节的字符串 slice:
let hello = "Зeeeeeeevdfbgth";
let s = &hello[0..4];

4 哈希map
和其它语言的Dict,dict,Dictionary等不太一样,Rust的HashMap很独特。

use std::collections::HashMap;

// 声明
let mut come_from = HashMap::new();
// 插入
come_from.insert("WaySLOG", "HeBei");
come_from.insert("Marisa", "U.S.");
come_from.insert("Mike", "HuoGuo");

// 查找key
if !come_from.contains_key("elton") {
    println!("Oh, 我们查到了{}个人,但是可怜的Elton猫还是无家可归", come_from.len());
}

// 根据key删除元素
come_from.remove("Mike");
println!("Mike猫的家乡不是火锅!不是火锅!不是火锅!虽然好吃!");

// 利用get的返回判断元素是否存在
let who = ["MoGu", "Marisa"];
for person in &who {
    match come_from.get(person) {
        Some(location) => println!("{} 来自: {}", person, location),
        None => println!("{} 也无家可归啊.", person),
    }
}

// 遍历输出
println!("那么,所有人呢?");
for (name, location) in &come_from {
    println!("{}来自: {}", name, location);
}

猜你喜欢

转载自blog.csdn.net/BaiHuaXiu123/article/details/88089137