File size: 3,855 Bytes
f63b320 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | "id","perguntas","saidas"
"1","Como declaro uma função em Rust?","```rust
fn soma(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!(""{}"", soma(3, 4)); // 7
}
```
Em Rust, a última expressão sem `;` é o retorno. `i32` é o tipo inteiro de 32 bits. `println!` é uma macro, não uma função."
"2","Como criar uma struct em Rust?","```rust
struct Pessoa {
nome: String,
idade: u32,
}
impl Pessoa {
fn new(nome: String, idade: u32) -> Self {
Pessoa { nome, idade }
}
fn apresentar(&self) -> String {
format!(""Olá, sou {} e tenho {} anos"", self.nome, self.idade)
}
}
fn main() {
let p = Pessoa::new(String::from(""Ana""), 25);
println!(""{}"", p.apresentar());
}
```
`impl` bloco define métodos da struct. `&self` é uma referência imutável à instância."
"3","Como trato erros em Rust com Result?","```rust
use std::fs::File;
use std::io::Read;
fn ler_arquivo(caminho: &str) -> Result<String, std::io::Error> {
let mut f = File::open(caminho)?;
let mut conteudo = String::new();
f.read_to_string(&mut conteudo)?;
Ok(conteudo)
}
fn main() {
match ler_arquivo(""dados.txt"") {
Ok(c) => println!(""{}"", c),
Err(e) => eprintln!(""Erro: {}"", e),
}
}
```
`?` propaga o erro para o caller. `Result<T, E>` é o tipo padrão para operações que podem falhar."
"4","Como faço um loop em Rust?","```rust
// Loop for
for i in 0..5 {
println!(""{}"", i);
}
// Loop while
let mut n = 0;
while n < 3 {
println!(""{}"", n);
n += 1;
}
// Loop infinito com break
let mut x = 0;
loop {
if x >= 10 { break; }
x += 1;
}
```
`0..5` é um range exclusivo (vai até 4). `0..=5` é inclusivo. `loop` roda até um `break`."
"5","Como uso ownership e borrowing em Rust?","```rust
fn main() {
let s1 = String::from(""Olá"");
let s2 = s1.clone(); // clona o conteúdo
println!(""{} {}"", s1, s2);
// Borrowing (empréstimo)
fn tamanho(s: &String) -> usize {
s.len()
}
let s3 = String::from(""Rust"");
println!(""{}"", tamanho(&s3));
}
```
Por padrão, atribar move a ownership. Use `&` para emprestar sem transferir ownership. `.clone()` duplica dados."
"6","Como trabalho com vectors em Rust?","```rust
let mut nums: Vec<i32> = Vec::new();
nums.push(1);
nums.push(2);
nums.push(3);
// Inicialização com valores
let frutas = vec![String::from(""maçã""), String::from(""uva"")];
// Iteração
for n in &nums {
println!(""{}"", n);
}
// Acesso
println!(""{}"", nums[0]); // 1
println!(""{}"", nums.get(0).unwrap()); // 1
```
`Vec<T>` é o array dinâmico de Rust. `.get()` retorna `Option<&T>`, seguro contra access out-of-bounds."
"7","Como criar enums com variantes em Rust?","```rust
enum Forma {
Circulo(f64),
Retangulo(f64, f64),
Quadrado(f64),
}
impl Forma {
fn area(&self) -> f64 {
match self {
Forma::Circulo(r) => std::f64::consts::PI * r * r,
Forma::Retangulo(l, a) => l * a,
Forma::Quadrado(l) => l * l,
}
}
}
fn main() {
let f = Forma::Circulo(2.0);
println!(""Área: {:.2}"", f.area());
}
```
Enums em Rust são muito poderosos — variantes podem carregar dados. `match` faz pattern matching exaustivo."
"8","Como criar e usar threads em Rust?","```rust
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!(""Thread: {}"", i);
thread::sleep(Duration::from_millis(10));
}
});
for i in 1..3 {
println!(""Main: {}"", i);
thread::sleep(Duration::from_millis(10));
}
handle.join().unwrap(); // espera a thread terminar
}
```
`thread::spawn` cria a thread; `.join()` bloqueia até terminar. Para compartilhar dados entre threads, use `Arc<Mutex<T>>`."
|