Type | has same type? |
has fixed size? |
can grow/shrink size? |
stack or heap |
---|---|---|---|---|
tuple | No | Yes | No | stack |
array | Yes | Yes | No | stack |
vector | Yes | No | Yes | --- |
enum | No | --- | No | --- |
HashMap | No | --- | --- | --- |
char
Character typeRust’s char type is the language’s most primitive alphabetic type
char
literals are specified with single quotes
string
literals are specified with double quotes
fn main() {
let c = 'z';
let z = 'ℤ';
let heart_eyed_cat = '😻';
}
&str
- String Literals Are Slicesfn main() {
let s = "Hello, world!";
}
String
- The String Typelet s = String::from("hello");
This kind of string can be mutated:
fn main() {
let mut s = String::from("hello");
s.push_str(", world!"); // push_str() appends a literal to a String
println!("{}", s); // This will print `hello, world!`
}
If we do want to deeply copy the heap data of the String, not just the stack data, we can use a common method called clone. We’ll discuss method syntax in Chapter 5, but because methods are a common feature in many programming languages, you’ve probably seen them before.
Here’s an example of the clone method in action:
fn main() {
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
}
tuple
Tuple Compound Typefn main() {
fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
let x: (i32, f64, u8) = (500, 6.4, 1);
println!("The value of y is: {} x is: {}", y, x.0);
}
The value of y is: 6.4 x is: 500
array
Array Compound Typeexample of when you might want to use an array
let months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
let january = months[0];
trim
- eliminate any whitespace at the beginning and end.The trim method on a String
instance will eliminate any whitespace at the beginning and end.
fn main() {
let guess = String::from(" hello ");
println!("before:{}", guess);
let guess = guess.trim();
println!("after:{}", guess);
}
before: hello
after:hello
parse
(shadowing) = parses a string into some kind of number.Shadowing - convert a value from one type to another type.
Shadowing lets us reuse the variable name rather than forcing us to create two unique variables, such as guess_str and guess.
let guess: u32
Result
typeResult
the same way by using the expect
method again.Err Result
variant because it couldn’t create a number from the string, the expect
call will crash and print the message we give it.Ok
variant of Result
, and expect
will return the number that we want from the Ok value.fn main() {
let guess = String::from(" 5 ");
println!("before:{}", guess);
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("after:{}", guess);
}
before: 5
after:5
fn main() {
let guess = String::from(" 5; ");
println!("before:{}", guess);
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("after:{}", guess);
}
before: 5;
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/main.rs:5:43
Result
- The Result enum.parse
is able to turn the string into a number, it will return an Ok value that contains the resulting number.
fn main() {
let guess = String::from(" 5 ");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => 0,
};
println!("Result: {}", guess);
}
Result: 5
parse
is not able to turn the string into a number, it will return an Err value that contains more information about the error.
fn main() {
let guess = String::from(" 5, ");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => 0,
};
println!("Result: {}", guess);
}
Result: 0
loop
- creates an infinite loop.break
exit the loopcontinue
continue the loopfn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
while
- Conditional Loops with whileuseful for a program to evaluate a condition within a loop
fn main() {
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
println!("LIFTOFF!!!");
}
for
- Looping Through a Collection with foruse a for loop and execute some code for each item in a collection.
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
}
}
Use a Range, which is a type provided by the standard library that generates all numbers in sequence starting from one number and ending before another number.
fn main() {
for number in (1..4).rev() {
println!("{}!", number);
}
println!("LIFTOFF!!!");
}