Rust Basic Syntax
Variables, basic types, functions, comments, and control flow are programming concepts that almost every programming language has.
These basic concepts exist in every Rust program, and learning them early will let you learn the use of Rust as quickly as possible.
Variables
First, it must be stated that Rust is a strongly typed language, but it has the ability to automatically infer variable types. This can easily be confused with weakly typed languages.
By default, variables in Rust are immutable, unless declared as mutable using the mut keyword.
let a = 123; // 不可变变量
let mut b = 10; // 可变变量
To declare a variable, you need to use the let keyword. For example:
let a = 123;
Developers who have only learned JavaScript are sensitive to this statement, while developers who have only learned C find it hard to understand.
After this declaration statement, the following three lines of code are all forbidden:
a = "abc";
a = 4.56;
a = 456;
The error in the first line is that once a is declared as 123, a is determined to be an integer, and a string-type value cannot be assigned to it.
The error in the second line is that automatic numeric conversion would lose precision, and Rust does not allow automatic data type conversions that lose precision.
The error in the third line is that a is not a mutable variable.
The first two errors are easy to understand, but what does the third mean? Isn't a a variable?
This involves a design made by the Rust language for high-concurrency safety: minimizing the ability to change variable values at the language level. So a's value is immutable. But this does not mean a is not a "variable" (variable in English); the official documentation calls a variable like a an "immutable variable".
If one part of the program we write runs under the assumption that a value never changes, while another part of our code is changing that value, then the first part of the code may not operate as intended. Errors caused by this reason are hard to find afterward. This is why the Rust language designed this mechanism.
Of course, making a variable "mutable" only requires a mut keyword.
let mut a = 123;
a = 456;
This program is correct.
The Difference Between Constants and Immutable Variables
Since an immutable variable is immutable, isn't it a constant? Why is it called a variable?
There is still a difference between variables and constants. In Rust, the following program is legal:
let a = 123; // 可以编译,但可能有警告,因为该变量没有被使用
let a = 456;
But if a were a constant, it would not be legal:
const a: i32 = 123;
let a = 456;
A variable's value can be "rebound", but before "rebinding" it cannot be changed privately, which ensures that in the region after each "binding" the compiler can fully reason about the program logic. Although Rust has the ability to automatically infer types, in some cases declaring the type is more convenient:
let a: u64 = 123;
Here a is declared as an unsigned 64-bit integer variable. If the type were not declared, a would be automatically inferred as a signed 32-bit integer variable, which has a great impact on the value range of a.
Data Type
Rust is a statically typed language. You can explicitly specify the type when declaring a variable, but you can usually rely on type inference.
**Basic types: **i32 (32-bit signed integer), u32 (32-bit unsigned integer), f64 (64-bit floating point), bool (boolean type), char (character)
Example
let
x
:
i32
=
42
;
let
y
:
f64
=
3.14
;
let
is_true
:
bool
=
true
;
let
letter
:
char
=
'A'
;
function
Rust functions are defined with the fn keyword, and the return type of a function is specified with the arrow symbol ->.
Example
fn
add
(
a
:
i32
,
b
:
i32
)
->
i32
{
a
b
}
If a function has no return value, the type defaults to () (i.e., the empty tuple).
Control Flow
if Expressions
Example
let
number
=
7
;
if
number
<
5
{
println!
(
"less than 5"
)
;
}
else
{
println
!
(
"greater than or equal to 5"
)
;
}
loop loop: loop is an infinite loop in Rust, and you can use break to exit the loop.
Example
let
mut
counter
=
0
;
loop
{
counter
+=
1
;
if
counter
==
10
{
break
;
}
}
while loop
Example
let
mut
number
=
3
;
while
number
!=
0
{
println
!
(
"{}!"
,
number
)
;
number
-=
1
;
}
for loop
Example
for
number
in
1
..
4
{
println
!
(
"{}!"
,
number
)
;
}
Ownership
Ownership in Rust is a unique memory management mechanism. Core concepts include ownership, borrowing, and reference.
Ownership Rules:
- Every value in Rust has an owner.
- A value can have only one owner at any time.
- When the owner goes out of scope, the value will be dropped.
let s1 = String::from("hello");
let s2 = s1; // s1 的所有权被转移给了 s2
// println!("{}", s1); // Compilation will fail here because s1 no longer owns the value
Borrowing and References: Borrowing allows referencing data without taking ownership, implemented through the & symbol.
fn main() {
let s = String::from("hello");
let len = calculate_length(&s); // 借用
println!("The length of '{}' is {}.", s, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
Structs
Structs are used to create custom types, and fields can contain multiple data types.
Example
struct
User
{
username
:
String
,
:
String
,
sign_in_count
:
u64
,
active
:
bool
,
}
let
user1
=
User
{
username
:
String
::
from
(
"someusername"
)
,
:
String
::
from
(
"someone@example.com"
)
,
sign_in_count
:
1
,
active
:
true
,
}
;
Enums
Enums allow defining one of several possible data types.
Example
enum
IpAddrKind
{
V4
,
V6
,
}
let
four
=
IpAddrKind
::
V4
;
let
six
=
IpAddrKind
::
V6
;
Pattern Matching (match)
match is a powerful control flow tool in Rust, similar to the switch statement.
Example
enum
Coin
{
Penny
,
Nickel
,
Dime
,
Quarter
,
}
fn
value_in_cents
(
coin
:
Coin
)
->
u8
{
match
coin
{
Coin
::
Penny
=>
1
,
Coin
::
Nickel
=>
5
,
Coin
::
Dime
=>
10
,
Coin
::
Quarter
=>
25
,
}
}
Error handling
Rust has two main error handling approaches: Result
Result:
Example
enum
Result
<
T
,
E
{
Ok
(
T
)
,
Err
(
E
)
,
}
fn
divide
(
a:
i32
,
b
:
i32
)
->
Result
<
i32
,
String
{
if
b
==
0
{
Err
(
String::
from
(
"Division by zero"
)
)
}
else
{
Ok
(
a
/
b
)
}
}
Option:
Example
fn
get_element
(
index
:
usize
,
vec
:
&
Vec
<
i32
)
->
Option
<
i32
{
if
index
<
vec.len
(
)
{
Some
(
vec
[
index
]
)
}
else
{
None
}
}Rust uses lifetimes to ensure the validity of references. Lifetime annotations are expressed with 'a and so on, but in common cases, the compiler infers them automatically.
Example
fn
longest
<
'a>(x: &'
a
str
,
y
:
&
'a str) -> &'
a
str
{
if
x.len
(
)
y.len
(
)
{
x
}
else
{
y
}
}
Shadowing
The concept of shadowing is different from "Override" or "Overload" in other object-oriented languages. Shadowing is the so-called "rebinding" just described; the quotation marks are used to temporarily stand in for the concept before it is introduced.
Shadowing refers to the mechanism by which a variable's name can be reused:
Example
fn
main
(
)
{
let
x
=
5
;
let
x
=
x
1
;
let
x
=
x
2
;
println
!
(
"The value of x is: {}"
,
x
)
;
}
The running result of this program:
The value of x is: 12
Shadowing and assignment of a mutable variable are not the same concept. Shadowing means reusing the same name to represent another variable entity, whose type, mutability, and value can all change. But assignment of a mutable variable can only change the value.
let mut s = "123";
s = s.len();
This program will produce an error: you cannot assign an integer value to a string variable.