A gotcha that got me, compiler warning would be helpful

My intent was to initialize a vector of size 3:

let mut cnts = vec![0usize, 3];

The code compiled with no problem, but when I ran it I got this message:

thread 'main' panicked at 'index out of bounds: the len is 2 but the index is 2', /rustc/a53f9df32fbb0b5f4382caaad8f1a46f36ea887c/src/libcore/slice/mod.rs:2701:14
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

WTF! It compiled, now what. So I started put print statements in the code to find out where it bombed. An hour later, I determined cnts was creating a vector of [0, 3] instead of [0, 0, 0].

Instead of vec![0usize, 3] it should have been vec![0size; 3] – a semicolon vs a coma.

I am sure this mistake has happened more than once to people and it would be really nice for the compiler to throw a warning message:

Hey, you wrote vec![x, y] did you really mean vec![x; y]?

A better delimiter character would probably eliminate most of these errors, but I guess it’s too late in the game to introduce that (or is it?).

You can’t warn here, as it would break legitimate usage of 2 element Vec.

3 Likes

Using vec![0, 3] is totally fine, because it will create a 2-element vector with the fields 0 and 3. You can’t have a warning for that.

Instead use a range based for loop, a la for i in &vec![0, 3] instead of index based loop which is kind of proscribed in Rust.

Stick to the usual guidelines and you’ll probably be fine.

Yes, I realize the code is valid (technically), I’m just saying the compiler could just put out a warning message. It would compile it as normal, but the (tired, distracted, novice) programmer would be given a chance to fix it if that wasn’t the intent, or ignore the warning (goodness knows I ignore a multitude of warnings about capitalizing constant variables all the time).

And people like me, who strictly do not accept warnings in their code and even use flags that lift warnings into errors have some piece of code that doesn’t compile anymore.

3 Likes

A programmer should never ever ignore warnings. Warnings are there for a good reason, to warn that something is probably odd.
If you don’t like the upper case style for globals use #![allow(non_upper_case_globals)] or better use the correct style.

Again: ignoring warnings is never a good approach.

1 Like

Getting a warning for this won’t be possible.

This does not mean that there is no solution to your problem: this is a case where mandatory trailing commas would ensure there is no mistake. Thus a custom macro can be used to solve this issue:

error: Error, expected trailing comma, such as `[0, 3, ]`
Hint: maybe you meant `[0; 3]` ?
...
37 |       let _v = my_vec![0, 3];
   |                ------------- in this macro invocation

3 Likes