Why doesn't a range starting with a negative number repeat?

I just started to learn Rust. During my first steps with this language, I found strange behavior when iteration is performed inside mainor in another function, as in the following example:

fn myfunc(x: &Vec<f64>) {
    let n = x.len();
    println!("    n: {:?}", n);
    for i in -1 .. n {
        println!("    i: {}", i);
    }
}

fn main() {
    for j in -1 .. 6 {
        println!("j: {}", j);
    }

    let field = vec![1.; 6];
    myfunc(&field);
}

As long as the loop in is maindisplayed correctly, myfuncnothing is printed for the loop inside , and I get the following output:

j: -1
j: 0
j: 1
j: 2
j: 3
j: 4
j: 5
    n: 6

What is the reason for this behavior?

+4
source share
1 answer

, usize, . , usize::MAX n, .

, :

let () = -1 .. x.len();

:

error: mismatched types:
 expected `core::ops::Range<usize>`,
    found `()`
(expected struct `core::ops::Range`,
    found ()) [E0308]
let () = -1 .. x.len();
    ^~

, slice::len usize. -1 - , , ( , i32).

(-1 as usize)..x.len().

, , , -1 . :

fn myfunc(x: &[f64]) {
    let n = x.len();
    println!("    n: {:?}", n);
    for i in 0..n {
        println!("    i: {}", i);
    }
}

, ​​ Rust. , :

warning: unary negation of unsigned integers will be feature gated in the future
     for i in -1 .. n {
              ^~

, &Vec<T> . &[T], , .

+7

Source: https://habr.com/ru/post/1606069/


All Articles