~$ cargo new hello_cargo
~$ cd hello_cargo
hello_cargo ~$ cargo build
hello_cargo ~$ cargo runFixed 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); }