2024-12-14 14:29:06 +00:00
# Rust Basics
2024-12-12 12:56:11 +00:00
### Tipos Genéricos
2024-12-14 14:29:06 +00:00
Crie uma struct onde 1 de seus valores pode ser de qualquer tipo
2024-12-12 12:56:11 +00:00
```rust
struct Wrapper< T > {
2024-12-14 14:29:06 +00:00
value: T,
2024-12-12 12:56:11 +00:00
}
impl< T > Wrapper< T > {
2024-12-14 14:29:06 +00:00
pub fn new(value: T) -> Self {
Wrapper { value }
}
2024-12-12 12:56:11 +00:00
}
Wrapper::new(42).value
Wrapper::new("Foo").value, "Foo"
```
2024-12-14 14:29:06 +00:00
### Option, Some & None
2024-12-12 12:56:11 +00:00
2024-12-14 14:29:06 +00:00
O tipo Option significa que o valor pode ser do tipo Some (há algo) ou None:
2024-12-12 12:56:11 +00:00
```rust
pub enum Option< T > {
2024-12-14 14:29:06 +00:00
None,
Some(T),
2024-12-12 12:56:11 +00:00
}
```
Você pode usar funções como `is_some()` ou `is_none()` para verificar o valor da Option.
### Macros
2024-12-14 14:29:06 +00:00
Macros são mais poderosas do que funções porque se expandem para produzir mais código do que o código que você escreveu manualmente. Por exemplo, uma assinatura de função deve declarar o número e o tipo de parâmetros que a função possui. Macros, por outro lado, podem aceitar um número variável de parâmetros: podemos chamar `println!("hello")` com um argumento ou `println!("hello {}", name)` com dois argumentos. Além disso, as macros são expandidas antes que o compilador interprete o significado do código, então uma macro pode, por exemplo, implementar um trait em um tipo específico. Uma função não pode, porque é chamada em tempo de execução e um trait precisa ser implementado em tempo de compilação.
2024-12-12 12:56:11 +00:00
```rust
macro_rules! my_macro {
2024-12-14 14:29:06 +00:00
() => {
println!("Check out my macro!");
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
}
2024-12-12 12:56:11 +00:00
}
fn main() {
2024-12-14 14:29:06 +00:00
my_macro!();
my_macro!(7777);
2024-12-12 12:56:11 +00:00
}
// Export a macro from a module
mod macros {
2024-12-14 14:29:06 +00:00
#[macro_export]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
2024-12-12 12:56:11 +00:00
}
```
### Iterar
```rust
// Iterate through a vector
let my_fav_fruits = vec!["banana", "raspberry"];
let mut my_iterable_fav_fruits = my_fav_fruits.iter();
assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry"));
assert_eq!(my_iterable_fav_fruits.next(), None); // When it's over, it's none
2024-12-14 14:29:06 +00:00
2024-12-12 12:56:11 +00:00
// One line iteration with action
my_fav_fruits.iter().map(|x| capitalize_first(x)).collect()
// Hashmap iteration
for (key, hashvalue) in & *map {
for key in map.keys() {
for value in map.values() {
```
### Caixa Recursiva
```rust
enum List {
2024-12-14 14:29:06 +00:00
Cons(i32, List),
Nil,
2024-12-12 12:56:11 +00:00
}
let list = Cons(1, Cons(2, Cons(3, Nil)));
```
### Condicionais
2024-12-14 14:29:06 +00:00
#### se
2024-12-12 12:56:11 +00:00
```rust
let n = 5;
if n < 0 {
2024-12-14 14:29:06 +00:00
print!("{} is negative", n);
2024-12-12 12:56:11 +00:00
} else if n > 0 {
2024-12-14 14:29:06 +00:00
print!("{} is positive", n);
2024-12-12 12:56:11 +00:00
} else {
2024-12-14 14:29:06 +00:00
print!("{} is zero", n);
2024-12-12 12:56:11 +00:00
}
```
2024-12-14 14:29:06 +00:00
#### correspondência
2024-12-12 12:56:11 +00:00
```rust
match number {
2024-12-14 14:29:06 +00:00
// Match a single value
1 => println!("One!"),
// Match several values
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
// TODO ^ Try adding 13 to the list of prime values
// Match an inclusive range
13..=19 => println!("A teen"),
// Handle the rest of cases
_ => println!("Ain't special"),
2024-12-12 12:56:11 +00:00
}
let boolean = true;
// Match is an expression too
let binary = match boolean {
2024-12-14 14:29:06 +00:00
// The arms of a match must cover all the possible values
false => 0,
true => 1,
// TODO ^ Try commenting out one of these arms
2024-12-12 12:56:11 +00:00
};
```
#### loop (infinito)
```rust
loop {
2024-12-14 14:29:06 +00:00
count += 1;
if count == 3 {
println!("three");
continue;
}
println!("{}", count);
if count == 5 {
println!("OK, that's enough");
break;
2024-12-12 12:56:11 +00:00
}
}
```
2024-12-14 14:29:06 +00:00
#### enquanto
2024-12-12 12:56:11 +00:00
```rust
let mut n = 1;
while n < 101 {
2024-12-14 14:29:06 +00:00
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
n += 1;
2024-12-12 12:56:11 +00:00
}
```
#### para
```rust
for n in 1..101 {
2024-12-14 14:29:06 +00:00
if n % 15 == 0 {
println!("fizzbuzz");
} else {
println!("{}", n);
}
2024-12-12 12:56:11 +00:00
}
// Use "..=" to make inclusive both ends
for n in 1..=100 {
2024-12-14 14:29:06 +00:00
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
2024-12-12 12:56:11 +00:00
}
// ITERATIONS
let names = vec!["Bob", "Frank", "Ferris"];
//iter - Doesn't consume the collection
for name in names.iter() {
2024-12-14 14:29:06 +00:00
match name {
& "Ferris" => println!("There is a rustacean among us!"),
_ => println!("Hello {}", name),
}
2024-12-12 12:56:11 +00:00
}
//into_iter - COnsumes the collection
for name in names.into_iter() {
2024-12-14 14:29:06 +00:00
match name {
"Ferris" => println!("There is a rustacean among us!"),
_ => println!("Hello {}", name),
}
2024-12-12 12:56:11 +00:00
}
//iter_mut - This mutably borrows each element of the collection
for name in names.iter_mut() {
2024-12-14 14:29:06 +00:00
*name = match name {
& mut "Ferris" => "There is a rustacean among us!",
_ => "Hello",
2024-12-12 12:56:11 +00:00
}
}
```
2024-12-14 14:29:06 +00:00
#### se deixar
2024-12-12 12:56:11 +00:00
```rust
let optional_word = Some(String::from("rustlings"));
if let word = optional_word {
2024-12-14 14:29:06 +00:00
println!("The word is: {}", word);
2024-12-12 12:56:11 +00:00
} else {
2024-12-14 14:29:06 +00:00
println!("The optional word doesn't contain anything");
2024-12-12 12:56:11 +00:00
}
```
#### enquanto deixar
```rust
let mut optional = Some(0);
// This reads: "while `let` destructures `optional` into
// `Some(i)` , evaluate the block (`{}`). Else `break` .
while let Some(i) = optional {
2024-12-14 14:29:06 +00:00
if i > 9 {
println!("Greater than 9, quit!");
optional = None;
} else {
println!("`i` is `{:?}` . Try again.", i);
optional = Some(i + 1);
}
// ^ Less rightward drift and doesn't require
// explicitly handling the failing case.
2024-12-12 12:56:11 +00:00
}
```
### Traits
2024-12-14 14:29:06 +00:00
Crie um novo método para um tipo
2024-12-12 12:56:11 +00:00
```rust
trait AppendBar {
2024-12-14 14:29:06 +00:00
fn append_bar(self) -> Self;
2024-12-12 12:56:11 +00:00
}
impl AppendBar for String {
2024-12-14 14:29:06 +00:00
fn append_bar(self) -> Self{
format!("{}Bar", self)
}
2024-12-12 12:56:11 +00:00
}
let s = String::from("Foo");
let s = s.append_bar();
println!("s: {}", s);
```
### Testes
```rust
#[cfg(test)]
mod tests {
2024-12-14 14:29:06 +00:00
#[test]
fn you_can_assert() {
assert!(true);
assert_eq!(true, true);
assert_ne!(true, false);
}
2024-12-12 12:56:11 +00:00
}
```
### Threading
#### Arc
2024-12-14 14:29:06 +00:00
Um Arc pode usar Clone para criar mais referências sobre o objeto para passá-las para as threads. Quando o último ponteiro de referência a um valor sai do escopo, a variável é descartada.
2024-12-12 12:56:11 +00:00
```rust
use std::sync::Arc;
let apple = Arc::new("the same apple");
for _ in 0..10 {
2024-12-14 14:29:06 +00:00
let apple = Arc::clone(&apple);
thread::spawn(move || {
println!("{:?}", apple);
});
2024-12-12 12:56:11 +00:00
}
```
#### Threads
2024-12-14 14:29:06 +00:00
Neste caso, passaremos à thread uma variável que ela poderá modificar.
2024-12-12 12:56:11 +00:00
```rust
fn main() {
2024-12-14 14:29:06 +00:00
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let status_shared = Arc::clone(&status);
thread::spawn(move || {
for _ in 0..10 {
thread::sleep(Duration::from_millis(250));
let mut status = status_shared.lock().unwrap();
status.jobs_completed += 1;
}
});
while status.lock().unwrap().jobs_completed < 10 {
println!("waiting... ");
thread::sleep(Duration::from_millis(500));
}
2024-12-12 12:56:11 +00:00
}
```