Rust is statically typed, ahead-of-time compiled language.
Rust has a strong, static type system. However, it also has type inference.
Rust developers are called Rustaceans.
Code example:
main
fn
main()
function is a starting point for any Rust program.
To define a function:
The main
function is special because it’s the entry and exit point of executable programs, and there are restrictions on what its return type can be for the programs to behave as expected.
Other than ()
the main
can also return a Result<(), E>
.
For now, you can read Box<dyn Error>
to mean “any kind of error.”
The main
function may return any types that implement the std::process::Termination
trait, which contains a function report
that returns an ExitCode
.
Rust style is to indent with four spaces, not a tab.
println!
- calls a Rust macro.
Most lines of Rust code end with a semicolon.
To compile a program and output a binary:
By default, Rust has a set of items defined in the standard library that it brings into the scope of every program. This set is called the prelude, and you can see everything in it in the standard library documentation. If a type you want to use isn’t in the prelude, you have to bring that type into scope explicitly with a
use
statement.
The
::
syntax in thelet mut guess = String::new();
line indicates thatnew
is an associated function of theString
type. An associated function is a function that’s implemented on a type, in this caseString
. Thisnew
function creates a new, empty string.
References are immutable by default. Hence, you need to write
&mut guess
rather than&guess
to make it mutable
Result
is an enumeration, often called an enum, which is a type that can be in one of multiple possible states. We call each possible state a variant.
Variables
Data types
Rust is an expression-based language.
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.