zoukankan      html  css  js  c++  java
  • collections

    Storing Lists of Values with Vectors

    Vector

    The first collection type we'll look at is Vec<T>, as known as a Vector. Vector allows you to store more than one value in a single data structure that puts all the values next to each other in memory.

    How to use a vector

    Let me explain the usage with a simple but classic instance:

    //vector
    fn ve() {
        //create a new instance
        let v: Vec<i32> = Vec::new();
        //it's mote common to create a vector that has initial values
        //as the compiler can infer the type i32 from the initial values, 
        //so we don't need the Vec<i32> annotation.
        let mut v = vec![1,2,3];
        
        //push in some values
        v.push(4);
        v.push(5);
    
        //two ways to access elements in a vector with index
        let third = &v[2];
        match v.get(3) {
            Some(third) => println!("vector third element is {}", third),
            None => println!("there is no third element"),
        }
        /*
         * differences between [] and get
         * []: give us a i32 type element or &i32 type if we use &
         * get: give us a Option<&T> type element
         */
        
        //what if we access an element with an unexisted index
        //let sixth = &v[5]; //panic when run the program
        let six = v.get(5); //return None
    
        /*
         * iterating over the values in a vector with the for loop
         */
        for i in &v {
            println!("{}", i);
        }
        //use mutable reference
        for i in &mut v {
            *i += 1;//we have to use the dereference operator(*) to get to the value in i before we can use the += operator
        }
    
        //pop: removes the last element from a vector and returns it
        println!("last element of the vector: {}", v.pop().unwrap());//unwrap is a Option<T> function to get the T value.
    
        //drain: creates a draining iterator that removes the specified range in the vector and yields the removed items.
        let dr: Vec<_> = v.drain(1..).collect();//collect is a function of iterator, we'll cover it later.
        assert_eq!(v.len(), 1);
    }
    

    Little details:

  • 相关阅读:
    django_开发报错
    SpringBoot 前后端数据参数交互
    消息队列学习笔记(一)
    2021年调用工商二维码退款查询接口
    2021年调用工商二维码退款接口
    2021年调用工商二维码生成接口及回调接口demo
    调用工商生成二维码接口文档的坑
    使用hutool工具类转换时间
    微信模板消息推送
    pom文件 spring-boot-maven-plugin 爆红
  • 原文地址:https://www.cnblogs.com/lunar-ubuntu/p/14328725.html
Copyright © 2011-2022 走看看