#!/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, } } }