Rust 002 — Variables, Functions, Conditionals, Loops
Constants Vs Variable
- Constants aren’t just immutable by default — they’re always immutable.
- Two sets of data types: scalar and compound
Scalar Types
A scalar type represents a single value. Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters
Floating
Rust also has two primitive types for floating-point numbers, which are numbers with decimal points. Rust’s floating-point types are f32
and f64
, which are 32 bits and 64 bits in size, respectively.
Char
Rust’s char
type is four bytes in size and represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII.
In format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
Tuples
Tuples have a fixed length: once declared, they cannot grow or shrink in size. The tuple without any values, ()
, is a special type that has only one value, also written ()
. The type is called the unit type and the value is called the unit value.
Expressions
Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value.
Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, and it will then not return a value.
Functions
Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow (->
). In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function.
If-else-else if
For if else blocks, Rust only executes the block for the first true condition, and once it finds one, it doesn’t even check the rest.
Because if
is an expression, we can use it on the right side of a let
statement to assign the outcome to a variable,
Remember that blocks of code evaluate to the last expression in them, and numbers by themselves are also expressions.
Loops, Labeled loops, while, for, Range
You can optionally specify a loop label on a loop that we can then use with break
or continue
to specify that those keywords apply to the labeled loop instead of the innermost loop.
Rust also supports while loop for for the safety and conciseness of for
loops make them the most commonly used loop construct in Rust.
fn main() {
let a = [10, 20, 30, 40, 50];for element in a {
println!(“the value is: {}”, element);
}
}
Ref: https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html