This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging

The interval Range

Range in Rust stands for an “interval” :

fn main() {let r = 1.10;
    for _i in i{
        / /...}}Copy the code

Note that in this syntax, an open interval is preceded by a closed interval. This syntax actually produces STD ::ops::Range<_>, which is defined in the library as follows:

pub struct Range<Idx>{
    pub start: Idx;
    pub end: Idx;
}
Copy the code

This construct implements the trait of Iterator and can therefore be applied to looping statements. There are several other ranges in Rust:

  • STD ::ops::RangeFrom represents a range with only a start and no end. Means:[start,...]

Similar to RangeTo and RangeFull. You can view the Rust document. Using the built-in functions mentioned above, we have the flexibility to loop through arrays of types that implement iterators.

    fn main() {let arr = [1.2.3.4.5];
        for i in&arr[..] {println!("{:? }",i)
        }
    }
    // 1, 2, 3, 4, 5
Copy the code

The border check

When we retrieve a value from an array, or when we iterate over a value that is not in the range of the array, rust will issue a panic error, causing the program to exit, as described in the previous article. This represents rust’s protection for the program to run safely. Second, in Rust, if we want to get an Index to an object of a type, we need that type to implement STD :: OPS ::Index trait, and if we also want to get permission to operate on that value, we need to implement STD :: OPS ::IndexMuttrait.

To prevent this type of error, if we are not sure whether our read operation is valid, we should use the get() method provided by rust to get the value of the index, which returns a value of type Result

:

let arr = [1.2.3];
println!("{:? }",arr.get(0));
println!("{:? }",arr.get(10));
//Some(1)
//None
Copy the code

Although Rust pretends to be gc-free, does it mean that Rust is not safe enough for panic caused by an out-of-bounds array? Rust does not encourage extensive use of index operations. Every index operation is “boundary checked”, which is less efficient than C++. Since C++ doesn’t perform this operation, this corresponds to the get_unchecked() operation in rust. In Rust, we should try to use iterators to get the values we want.

use std::iter::Iterator;
let arr = [1.2.3.4.5];
for (index,value) in arr.iter().enumerate(){
    println!("{:? }",index,value);
}
let i = v.iter().filter(|&x| *x*2= =4) println1 ("{:? }", I);Copy the code

In this way, through the Iterator method to improve the efficiency of the program running, but also reduce the probability of error in our program, is a good development habit.