Clube do Livro #19
struct Meters(u32);
struct SquareMeters(u32);
fn area(width: Meters, height: Meters) -> SquareMeters {
//
}Clube do Livro #19
use std::collections::HashMap;
#[derive(Debug)]
struct People(HashMap<usize, String>);
impl People {
fn new() -> Self {
return Self(HashMap::new());
}
fn add(&mut self, name: String) -> bool {
let does_contain = self.0.values().any(|val| *val == name);
if !does_contain {
self.0.insert(self.0.len() + 1, name);
}
!does_contain
}
}
fn main() {
let mut people = People::new();
people.add(String::from("Fulano"));
let result2 = people.add(String::from("Fulano"));
assert_eq!(false, result2);
people.add(String::from("Ciclano"));
people.add(String::from("Beltrano"));
println!("{:#?}", people)
}
Clube do Livro #19
// um simples apelido para o tipo i32
type Kilometers = i32;
// um caso mais complexo de um trait object com lifetime
type Thunk = Box<dyn Fn() + Send + 'static>;
Clube do Livro #19
use std::fmt;
use std::io::Error;
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error>;
fn flush(&mut self) -> Result<(), Error>;
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>;
fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>;
}
// O mesmo código com o sinônimo:
type Result<T> = std::result::Result<T, std::io::Error>;
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize>;
fn flush(&mut self) -> Result<()>;
fn write_all(&mut self, buf: &[u8]) -> Result<()>;
fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>;
}Clube do Livro #19
use std::process::exit;
fn the_answer() -> ! {
exit(42);
}let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
Clube do Livro #19
fn main() {
let s1: str = "Hello there!";
let s2: str = "How's it going?";
}Clube do Livro #19
fn generic<T>(t: T) {
// código
}
// é o mesmo que:
fn generic<T: Sized>(t: T) {
// código
}Clube do Livro #19
fn generic<T: ?Sized>(t: &T) {
// código
}Clube do Livro #19
@felubra
twitter, github, telegram:
Clube do Livro #19