Quick Rust
Posted on September 2, 2022
Tags: codeetc
1 Cargo
cargo new helloworld
cargo run helloworld
2 Rust
- Rust has no classes
- Rust mainly uses struct (Product Types) and enum (Sum Types)
impl
are like pointer receivers in Golangimpl
lets struct have methods
pub struct LList {
: i32,
x : Option<Box<LList >>
next}
impl LList {
fn get(&self) -> i32{
return self.x;
}
}
fn main() {
let mut nodeA = LList{x :8, next: None};
let nodeB = LList{x: 33, next: None};
.next = Some(Box::new(nodeB));
nodeAif let Some(i) = nodeA.next {
println!("{:?}",i.get());
}
}
3 vector, range loops
let mut vec1 = vec![1,2,3];
// (1..10) is a range type
for i in (1..10){
..
}
convert range to vector. Why? because iter()
doesnt work on range
let mut v3 :Vec<i32> = (1..10).collect();
//build a vector of tuples
let v4: Vec<(&i32,&i32)>= v3.iter().map(|x| (x,x)).collect();