Compound Data Type of Rust

Time:2021-7-24

summary

Long time no updaterustRelated content, update a waveRustLet’s talk about the content of this articleRustComposite data types in.

Composite Type

Composite data typeIs a data type, which can be composed of original basic data types and other composite types to form a composite type action, also known as combination.

This article introducesRustThere aretuplearraystructenumSeveral composite types.

tuple

tupleNamelytupleTuple type is a composite type composed of multiple elements of different types()Parentheses organize elements together into a new data type. The length of the tuple is fixed when it is defined and cannot be modified. If the data type of the element is specified, your element must be seated according to the number!!! Otherwise, the compiler will teach you a lesson!

example:

fn main() {
    //Specify data type
    let tup_type:(i8,i32,bool) = (21,-1024,true);
    //Deconstruction element
    let (one,two,three) = tup_type;
    //Two dimensional tuple
    let tup_2d:(f64,(i8,i32,bool)) = (3.1415927,(one,two,three));
    println!("tup_2d = {:?}",tup_2d);
    //Index
    println!("π = {:?}",tup_2d.0);
}

There are several ways to access tuples. They can be accessed through subscripts or by using deconstruction assignment to new variables, but iterators are not supported.

for v in tup_2d.1.iter() {
        println!("{}",v)
}
   Compiling playground v0.0.1 (/playground)
error[E0599]: no method named `iter` found for tuple `(i8, i32, bool)` in the current scope
  --> src/main.rs:10:23
   |
10 |     for v in tup_type.iter() {
   |                       ^^^^ method not found in `(i8, i32, bool)`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0599`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

tupleEach element of can be of a different type, so you cannot iterate over it. Tuples are not even guaranteed to store data in the same order as type definitions, so even if you implement them yourselfIterator, they are not suitable for effective iterations.

But if the element supports implementationIteratorYou can pass.iter()Perform iterative access.

    let mut arrays:[usize;5] = [0;5];
    
    for i in 0..5 {
        arrays[i] = i+1;
    }
    
    println!("{:?}",arrays);
    
    let tup_arr:(&str,[usize;5]) = ("tup_arr",arrays);
    
    println!("{:?}",tup_arr);
    
    for v in tup_arr.1.iter() {
        println!("{}",v)
    }

For example, the element on is aarrayRustLike other languages, an array in is a composite type composed of a group of elements of the same type. The underlying storage of the array is a continuous memory space.

array

RustThe array declaration in is[T;n]In the past,TIs the element type,nIt is the number of pits in this group of elements. When creating, the type and size can be removed, and the program will automatically infer.

//Array
    let arr:[f32;3] = [1.0,2.2,3.33];
    
    println!("{:?}",arr);
    
    //Type automatic derivation
    let arr_infer = ["Hello",",","World!"];
    
    let mut str = String::new();
    //Iterator
    for v in arr_infer.iter() {
        str.push_str(v);
    }
    
    println!("str = {}",str);

Click to view the tuple code case

enum

Enumeration types, if you’ve done it beforeJavaRelated development should be no stranger inRustIt’s in there, tooenumerationType. Enumeration type is a user-defined data typeenumKeyword to declare,bodyIt can contain multiple user-defined enumeration values. Enumeration can be used to limit the range of a value or type.

    #[derive(Debug)]
    enum Gender {
        Boy,
        Girl,
    }

The above defines a type name asGenderEnumeration of,BoyandGirlIs an enumeration of available values,#[derive(Debug)]Note is to letGenderAutomatic implementationDebug taritLater articles will be in-depth.

struct

Structure can assemble some user-defined data types into a new user-defined data type through existing typesstructKeyword can create a structure, structure field formatname:typenameIs the structure field name,typeIs the type of field. It is immutable by default.

fn main() {

    //Enumeration current value range
    #[derive(Debug)]
    enum Gender {
        Boy,
        Girl,
    }
    
    //Define a structure
    #[derive(Debug)]
    struct Programmer<'skill> {
        name: String,
        skill: [&'skill str; 3],
        sex: Gender,
    }
    
    //Create an instance
    let engineer = Programmer {
        Name: String:: from ("Jaco Ding"), // string type content is variable
        Skill: ["Java", "go", "rust"], // an array of string facet types with length of 3
        Sex: Gender:: boy, // restrict parameter types through enumeration
    };
    
    println!("engineer = {:?}",engineer);
}

With a custom type, that isstructYou can handle some special requirements through custom types. For example, the following code defines an element type asProgrammerCount Reg2Array of.

    let Doris = Programmer {
        name: String::from("Doris"),
        skill: ["Vue","TypeScript","JavaScript"],
        sex:Gender::Girl,
    };
    
    let Jaco = Programmer {
        name: String::from("Jaco"),
        skill: ["Java","Go","Rust"],
        sex:Gender::Boy,
    };
    
    let employees:[Programmer;2] = [Doris,Jaco];
    
    for e in employees.iter() {
        println!("{:?}",e)
    }

structural morphologyProgrammerUpper<'skill>solveskillThe life cycle of arraysundeclared lifetime, ownership, ownership isRustThe core knowledge points of the language are slowly updated in the following articles.

Summary

RustThere are also two special structures in the structure:Tuple structureSingle structureEnumeration is also availableWith parametersEnumeration of… This article summarizes the use of common composite types, which is not in-depth.

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]