#!/bin/bash mkdir learn cd learn cargo init ## 該命令會在當前目錄下初始化一個 ## 目錄下會出現一個Cargo.toml文件,這是Cargo的配置文件 ## 還有一個src目錄,目錄中包含一個main.rs的初始文件 cargo run ## 命令會編譯並運行程序 cargo build ## 編譯工程
fn main(){}
fn main(){ let world = "world"; println!("hello, {}!", world); } //該例子中能夠看出來,變量定義使用關鍵字 let,字符串格式化中的佔位符采用 {}
->
fn main() { let x:i32; let y:i32; x = 10; y = 5; println!("x = {}, y = {}", x, y); println!("add(x, y) = {}", add(x,y)); } fn add(x:i32, y:i32) ->i32{ x+y // return x+y; }
let val:i32 = 1
fn foo(_x :&'static str) -> &'static str{ "world" } fn main(){ println!("hello, {}!", foo("bar")); }
靜態字符串變量 &'static strshell
注意:在rust中,str
是關鍵字,不能用做變量名數組
let (x,y) = (5, 'a') // 類型分別是i32,char
let x:i32 =10; x = 6; // ^^^^^ cannot assign twice to immutable variable
mut
關鍵字let mut x:i32 = 10 x = 6
字符串,Rust中存在兩種字符串類型,str和String。安全
let x = "hello world!"; let y:&str = "hahahhahahah";
String::from
初始化該類型let x = String::from(「Hello, World」); let y: String = String::from(「Isn’t it a wonderful life?");
{ let mut s1 :&str = "s1 is &str"; let mut s2 :String = String::from("s2 is String"); println!("{}, {}", s1, s2); // s1 is &str, s2 is String s1 = "s1 is changed"; s2 = String::from("s2 is changed"); println!("{}, {}", s1, s2); // s1 is changed, s2 is changed }
let x = [1, 2, 3]; let y: [i32; 3] = [4, 5, 6];
let x = vec![1, 2, 3]; let y: Vec<i32> = [4, 5, 6];
let x = (5, 'A'); let y : (i32, char) = (12, 'c'); let v = x.0 // v == 5 let a = y.1 // a == 'c'
全部權bash
// String的長度是可變的,分配在堆中,因此這裏的會發生全部權移動。 // 在Rust中,這個過程稱之爲移動move,即本來x的值移動到了y上,x失效了。 fn main(){ let x = String::from("hello"); // x是"hello" let y = x; // y是「hello」,這時x已經失效 println!("x is {}, f(x) is {}",x, y); // 會出錯,由於x失效了。 }
借用併發
impl
做爲實現結構體方法的關鍵字,方法的輸入參數中第一個是self
。調用採用.
impl
範圍內,輸入參數沒有self
的方法,即爲關聯函數。調用使用:
impl
塊// 定義一個結構體 struct Rect{ width: i32, length: i32, } // 方法 impl Rect{ fn Area(&self) -> i32{ self.width * self.length } } // 關聯函數 impl Rect{ fn Square(w:i32) -> Rect{ Rect{width :w, length: w, } } }