Skip to content

Instantly share code, notes, and snippets.

@keegoo
Last active January 17, 2025 14:55
Show Gist options
  • Select an option

  • Save keegoo/50027dbf6c0bf61652f58777a1d60b6a to your computer and use it in GitHub Desktop.

Select an option

Save keegoo/50027dbf6c0bf61652f58777a1d60b6a to your computer and use it in GitHub Desktop.
my Rust cheat sheet

Table of Contents

  • Cargo
  • Array
  • 简单数字类型。
  • 简单字符串类型。
  • 字典类型。
  • 自定义类型。
  • 输出
  • 条件
  • 循环
  • class
  • import & export
  • map/filter/reduce.

Cargo

~$ cargo new hello_cargo
~$ cd hello_cargo
hello_cargo ~$ cargo build
hello_cargo ~$ cargo run

Array

Fixed size array.

let mut ary: [i32; 5] = [0; 5];    // default element value 0.
ary[0] = 10;
println!("{:?}", ary);
println!("{:?}", &ary[0..3]);      // print first 3 elements.

Re-sizable array.

// By definition, arrays have a length defined at compile time. So it's not possible to create a dynamic length array. But you can use a Vec. let mut vec: Vec = Vec::new(); // vec! macro can be used to initialize a vector let mut xs: Vec = vec![1, 2, 3];

vec.push(1); vec.push(2);

println!("{:?}", vec);

// loop array (works 1.53.0+) for x in ary { println!("{:?}", x) }

// ========== ========== // instance and static method struct Rectangle { x: f64, // length y: f64, // width }

impl Rectangle { // static method fn new(length: f64, width: f64) -> Rectangle { Rectangle {x: length, y: width} }

// instance method // &self is sugar for self: &Self, where Self is the type of the caller object. In this case Self = Rectangle fn area(&self) -> Rectangle { self.x * self.y } }

// ========== ========== // enum enum IpAddrKind { V4, V6, }

struct IpAddr { kind: IpAddrKind, address: String, }

let home = IpAddr { kind: IpAddrKind::V4, address: String::from("127.0.0.1"), }

// ========== ========== // functions visibility mod dog { // all functions are private by default fn private_function() {} // pub make them public pub fn public_function() {} }

// ========== ========== // for loop with Range let number = 1..10; // or // let number = std::ops::Range { start: 1, end: 10 }; for i in number { println!("i is {}", &i); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment