rust学习第7章

rust学习第7章

本文字数:861  阅读时长:2分钟

访客数:加载中... | 阅读量:加载中...

常用的集合

Vector

  • 由标准库提供
rust
fn main()
{
    let v:Vec<i32> = Vec::new();
    //也可以使用初始值创建Vec<T> 使用vec!宏
    let v = vec![1,2,3];//自动识别为Vec<i32>
}
  • 基础用法
rust
let mut v = Vec::new();
//添加元素
v.push(1);
v.push(2);
v.push(3);
v.push(4);
//删除元素
//1.作用域内有效 超出作用域自动清理
let mut v = vec![1, 2, 3, 4, 5];
// 1. pop() - 删末尾
v.pop();                    // [1,2,3,4]//返回Option<T>可以忽略也可以获取let mut a = v.pop();
// 2. remove() - 按索引删
v.remove(1);                // [1,3,4]  O(n)
// 3. swap_remove() - 快速删(不保序)
v.swap_remove(0);           // [4,3]    O(1)
// 4. retain() - 按条件批量删
v.retain(|&x| x > 2);       // [4,3]
// 5. clear() - 清空
v.clear();                  // []
println!("{:?}", v);
//读取元素
let a:&i32 = &v[2];//第三个元素//如果超出范围就会引起恐慌
v.get(2)//他也有返回值Option<&T> 也可以不用但是用他一般就会通过match防止恐慌
match v.get(2){
    Some(x) => println("有值");
    None => println("没值");
}

String

  • 很多Vec的操作都可用于Stirng
rust
fn main()
{
    //创建一个String
    let mut s = String::new();
   	let a = String::from("inisial contents");
    let data = "inisial contents";
    let b = data.to_string();
    let c = "inisial contents".to_string();
    //添加一个String
    s.push_str(&a);
    s.push('l');//添加单个字符
    let s3 = s + &a;//s消失a保留
    let s4 = format!("{}-{}-{}",s,a,data);
    //获取长度
    let len = String::from("hela").len();
    //string无法用[]取部分
}

字节 标量值 字形簇

字节

rust
let a = String::from("halo");
let b = a.bytes();

标量值

rust
let a = String::from("halo");
let b = a.chars();

字形簇

rust
//标准库中没有 老麻烦了

String切片

rust
let hello = "123456789";
let a = &hello[0..4];
//a = 1,2,3,4

对于汉字等其他语言文字 占用两个字节时 如果切割不是边界就会引起恐慌

rust
let hello = "你好";
let a = &hello[0,3];
//恐慌因为索引2不是边界

HashMap<K,V>

键值对形式存储

rust
use std::collections::HashMap;
fn main()
{
    //创建一个hashmap
    let mut scores: HashMap<String,i32> = HashMap::new();
    //或者你也可以这样
    let mut a = HashMap::new();
    a.insert(String::from("Blue"),10);
    //差一个值也行
    //在或者
    let teams = vec![String::from("Blue"),String::from("Yellow")];
    let intial = vec![10,50];
    let s :HashMap<_ , _> = teams.iter().zip(intial.iter()).collect();
    //获取值
    let temp = s.get(&String::from("Blue"));
    match temp{
        Some(s) => println!("{}",s),
        None => println!("None"),
    };
    //遍历
    for(k,v) in &scores{
        println!("{}: {}",k,v);
    }
    //替换
    s.insert(String::from("Blue"),25);
    //直接替换原有的
    //检查是否存在
    let ee = s.entry(String::from("Yellow"));
    let e = s.entry(String::from("Red"));
    //如果不存在
    e.or_insert(50);//就执行这个返回这个值的可变引用
}