Confusing error

Well I'm starting over with rust again, using a basic book (Carlo Milanesi, Beginning Rust) and encountered a confusing error.

Basically when writing following source code.

fn main() {
     for n in 1..10 {
         print!("{} ", n);
    }
}

it does compile on my computer, however when running the exe it throws a syntax error.
Now the troublesome part is this does work on playground, so I am tad confused.

Using the 1.62.0 build of the compiler. Win10 and so far everything has compiled and worked fine.

A syntax error should not be thrown at runtime. What is the error exactly? Maybe you can share a (partial) screen shot of the actual message or paste it here?

1 Like

it just reads "syntax error." .. well "Syntaxfehler." as I'm have a computer with german language setting.

1 Like

I assume that "for" is a special name in the Windows shell. The error is from the shell, not from Rust. Try to rename the program from "for" to "somename".

2 Likes

thanks, that solved it, will keep that in mind in the section of things I now know. :sweat_smile:

actually such code does not even compiles, ... is not a operator now.

 --> test.rs:2:11
  |
2 | for n in 1...10{
  |           ^^^
  |
help: use `..` for an exclusive range
  |
2 | for n in 1..10{
  |           ~~
help: or `..=` for an inclusive range
  |
2 | for n in 1..=10{
  |   

don't know what's wrong with your rustc, but such code should not compile.

the syntax error is another problem:

when you enter for in cmd and press enter, it almost always return syntax error.

$ LC_ALL=C wine cmd
Microsoft Windows 6.1.7601

Z:\me>for
Syntax error

Z:\me>

sorry was me mistyping in the posting I actually used 1..10 in code.

I think the "..." was a typo when copying the code here to the forum (or a typo that has been fixed meanwhile). The main error was naming the program "for", which can't be called by typing "for" in the Windows shell.

Not a typo, this is actually Discourse transforming .. and ... outside if inline code / code blocks into . It leads to confusion now and then :smile:

1 Like

Note that for _ in 1..10 does not count to 10 but only up to 9.

fn main() {
    let mut s = 0;
    for _ in 1..10 {
        s += 1;
    }
    assert_eq!(s, 9);
}

(Playground)

Compare with "..=" instead of "..":

fn main() {
    let mut s = 0;
    for i in 1..=10 {
        println!("{i}");
        s += 1;
    }
    assert_eq!(s, 10);
}

(Playground)