Declares an integer x
with value 1
.
let x: i32 = 1;
Declares a floating-point y
with value 3.14
.
let y: f64 = 3.14;
Declares a boolean z
with value true
.
let z: bool = true;
Declares a character a
with value 'a'
.
let a: char = 'a';
Declares a string s
with value "hello"
.
let s: String = String::from("hello");
If x
is greater than 5
, print "x is greater than 5". Otherwise, print "x is not greater than 5".
if x > 5 {
println!("x is greater than 5");
} else {
println!("x is not greater than 5");
}
Loop indefinitely, printing "Loop forever!".
loop {
println!("Loop forever!");
}
While x
is greater than 5
, print "x is greater than 5".
while x > 5 {
println!("x is greater than 5");
}
For i
in the range 0
to 5
, print i
.
for i in 0..5 {
println!("{}", i);
}
Match x
to different patterns and execute code accordingly.
match x {
1 => println!("one"),
2 => println!("two"),
_ => println!("anything"),
}
Defines a function add
that takes two i32
parameters and returns an i32
.
fn add(x: i32, y: i32) -> i32 {
x + y
}
Calls the function add
with arguments 5
and 7
, and stores the result.
let result = add(5, 7);
Defines a closure add
and calls it with arguments 5
and 7
.
let add = |x, y| {
x + y
};
let result = add(5, 7);
s1
is no longer valid after its ownership is moved to s2
.
let s1 = String::from("hello");
let s2 = s1;
s1
is still valid after s2
borrows a reference to s1
.
let s1 = String::from("hello");
let s2 = &s1;
s1
is mutable and s2
borrows a mutable reference to s1
.
let mut s1 = String::from("hello");
let s2 = &mut s1;
Defines a struct Point
with fields x
and y
.
struct Point {
x: i32,
y: i32,
}
Instantiates a Point
with x
as 5
and y
as 7
.
let p = Point {
x: 5,
y: 7,
};
Defines an enum Direction
with variants Up
, Down
, Left
, and Right
.
enum Direction {
Up,
Down,
Left,
Right,
}
Instantiates a Direction
as Up
.
let dir = Direction::Up;
Defines a module math
with a public function add
.
mod math {
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
}
Imports the function add
from the module math
.
use math::add;
Creates a vector v
with elements 1
, 2
, 3
.
let v = vec![1, 2, 3];
Creates a string s
with value "hello"
.
let s = String::from("hello");
Creates a mutable hash map scores
.
let mut scores = HashMap::new();
Causes the program to panic with a custom error message.
panic!("This is an unrecoverable error.");
Tries to open a file and panics with a custom error message if it fails.
let f = File::open("file.txt").unwrap_or_else(|error| {
panic!("Problem opening the file: {:?}", error)
});
Spawns a new thread that prints numbers from 1
to 10
.
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
}
});
Defines a macro say_hello
that prints "Hello, world!".
macro_rules! say_hello {
() => {
println!("Hello, world!");
};
}
Invokes the macro say_hello
.
say_hello!();