In Rust we’ve got if
statement, similar to C or C++, and also if
expressions, of the kind found for example in Python.
We’ve also got three keywords for creating loops: for
, loop
and while
.
Github: https://github.com/caveofprogramming/rust/
Logical Operators
These seem to be the same as C++, C and Java. Here is logical and, or and not (with and again) respectively.
This prints:
false
true
true
‘If’ Statements
If statements work similarly to C, C++ or Java, with optional else if
and else
blocks.
Note, there are no round brackets around the condition. Also, Rust will not consider a zero to be false; you have to put an actual condition in there.
‘If’ Expressions
Rust has an expression form of ‘if
’, like Python or Kotlin. In C++ or Java we’d have to use the ternary operator instead.
This is an expression that evaluates to one of two things.
The following code prints “Take jacket”.
Note there are no semi-colons inside the two blocks, and the values in the two blocks must be of the same type.
‘For’ Loops
‘For
’ loops are use a range-based syntax, similar to that found in Python or Kotlin. We don’t have the for(;;)
syntax that’s found in C.
0..3
ranges over the numbers 0, 1, 2 (exclusive range, excluding the end number) while 0..=3
ranges over 0, 1, 2, 3 (inclusive range, including the end).
I used print!()
here to create output all on the same line, and println!()
just to create a newline.
If you want to count backwards, you can add on rev()
. Then the range needs to be in round brackets.
‘While’ Loops
‘While
’ loops work much the same way as in other languages, with the familiar break and continue keywords.
‘Loop’ Loops
There’s also a loop
keyword, which creates an infinite loop. To stop it, you have to use the break
keyword.
This prints:
1 3 4 5
Labels
You can use labels to break out of an outer loop from within an inner loop. Labels are prefixed with an apostrophe whenever you refer to them.
This prints:
0,0 0,1 0,2 0,3 0,4
1,0 1,1 1,2 1,3 1,4
2,0 2,1 2,2 2,3
Labels don’t seem to work in while
loops, at least at the moment, but you can use them with for
and loop
.
Ah John - you spoilt us with the charm and elegance of Java! It is such a beautifully structured language. But I understand that had a trade off - the JVM made code run slower.
I remember you pulling in those graphics libraries in C++ - MDL wasn't it? Although you taught it exceptionally well as always, I did not like C++. I'm keeping faith with your judgment to follow this Rust train.
As for the vi/emacs debate, I had been a Windows guy for years envying those guys with access to Sun Workstations. (I am still not fluent in the C shell for that reason, I am still winging it). I saw them using those weird looking editors and had no idea what they were doing. Can you maybe give us a tutorial on vi to get us up to speed?