rust笔记1

编程入门 行业动态 更新时间:2024-10-28 18:34:02

rust<a href=https://www.elefans.com/category/jswz/34/1770047.html style=笔记1"/>

rust笔记1

1. 作用域

fn main() {let a = "JOJO";{let a = "DOI";println!("{}",a)}println!("{}",a)
}

2.常用类型

  • [T, N] : 拥有类型T, N个元素的数组
  • 数组 array
let mut array: [i32; 4] = [0; 4];
array[1] = 10;
for x in &array {println!("{}",x);
}
  • 向量 vec
//创建空vec
let v: Vec<i32> = Vec::new();
//宏创建vec
let v : Vec<i32> = vec![];
//创建可变vec
let mut v = vec![1,2,3];
v.push(10);
let e = v.pop();
v[2] = v[2] + 10;
  • str
  • String即 vec:Vec
let mut s = String::new();
let mut hello = String::from("world");
s.push('w');
s.push_str("string: &str");
println!("{}",s)

3.类型转换

  • as 显示转换
fn main() {let a = 64.1415_f32;let b = a as u8;let c = b as char;println!("{}, {}, {}",a,b,c)
}

4.循环

  • loop
  • while
//很平常的while循环
while running_size > 0 {self.swap_element(0, running_size);self.shiftup(0,running_size);running_size -= 1;}//与let Some搭配使用 (很强大)
while let Some(mut node) = stack.pop() {node.visit_node();if let Some(ref mut l) = node.left{stack.push(l);}if let Some(ref mut r) = node.right{stack.push(r);}}
  • for
for n in 0..101 {// a = [1,2,3,4] a.iter()if n % 15 ==0{println!("fizzbuzz");}else if n % 3==0{println!("fizz");}else{println!("buzz");}}

5.函数

fn is_divisible_by(lhs: uint, rhs: uint) -> bool {// Corner case, early returnif rhs == 0 {return false;}// This is an expression, the `return` keyword is not necessary herelhs % rhs == 0 
}

6.模块

例子…

  • 目录结构如下
  • data_structures/mod.rs描述如下

  • main.rs描述如下

7.匹配

//match功能很强大
let num : i32 = 13;
match num {1 => println!("first"),2|3|4 => println!("素数"),13...19 => println!("青少年"),_ =>  println!("不知道是啥"),}let b : bool = true;let c :i8 = match b {true => 1,false =>0,//这里因为bool类型本身只有两个状态,写不写都行};let p = (2,-1);
println!("{:?}",p);
match p {(x,y) if x==y => println!("双胞胎"),_=> println!("啥都没有"), //必须有默认行为
}

其中|用于匹配多个值,…匹配一个范围 (包含最后一个值),并且 _ 在这里是必须的, 因为match强制进行穷尽性检查 (exhaustiveness checking),必须覆盖所有的可能值。

8.全局变量

static PI:f64 = 3.14;
static LANGUAGE: &'static str = "Rust";
fn main() { println!("{}", LANGUAGE);println!("{}",PI);
}

9.输入输出流

  • 输入流例子1
use std::io;
fn read_input() -> io::Result<()> {let mut input = String::new();try!(io::stdin().read_line(&mut input));println!("You typed: {}", input.trim());Ok(())
}
fn main() {read_input();
}
  • 输入流例子2
use std::io;
fn main() {let mut string = String::new();println!("input sth please!");io::stdin().read_line(&mut string).expect("ERROR");println!("你说了木大是吗 ? {}",string)}
  • 读取文件
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::io;
fn main() {let path = Path::new("hello.txt");let display = path.display();//打开文件只读模式let mut file = match File::open(&path) {Err(why) => panic!("can't open {} : {}",display, Error::description(&why)),Ok(file) => file,};let mut string = String::new();match file.read_to_string(&mut string){Err(why) => panic!("can't open {} : {}",display, Error::description(&why)),Ok(_) => println!("{} has {}",display, string),}
}
  • 写文件
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::io;
fn main() {let path = Path::new("hello.txt");let display = path.display();//只写模式let mut file = match File::create(&path) {Err(why) => panic!("can't create {} : {}",display, Error::description(&why)),Ok(file) => file,};let mut string = String::new();string.push_str("string: &str");match file.write_all(string.as_bytes()){Err(why) => panic!("can't open {} : {}",display, Error::description(&why)),Ok(_) => println!("{} has {}",display, string),}
}

10.Box

//在堆上分配内存
let bp  = Box::new(Pair{first:1,second:2});
#[derive(Debug)]//二叉树
type BinNodeEnum<K,V> = Option<Box<BinNode<K,V>>>;
pub struct BinNode<K,V> where K: std::cmp::PartialOrd+ std::fmt::Debug{ //节点left : BinNodeEnum<K,V>,right : BinNodeEnum<K,V>,pub key : K,pub value : V,
}
  • 注意解构时 不用带Box
pub fn insert_nonrecursive(&mut self,k:K,v:V) {   let mut node = self;loop {match node.key<=k {true => {if let Some(ref mut right) = node.right { //注意这里node = right;}else{node.right = Some(Box::new(BinNode::new(k, v)));break;}},false =>{if let Some(ref mut l) = node.left {node = l;}else{node.left = Some(Box::new(BinNode::new(k, v)));break;}},}}}

11.结构体

struct Foo{x:(u32,u32),y:u32} //定义结构体
let f = Foo{x: (1 ,2 ), y:3 }; //创建结构体
let Foo {x,y} = f; //结构结构体
println!("x={:?},y={}",x,y);
let Foo { x: (a, b), y } = f;
println!("a = {}, b = {},  y = {} ", a, b, y);
let Foo{x,..} = f;//带省略的结构
println!("x={:?}",x);/*
需要注意,Rust在语言级别不支持域可变性 (field mutability),所以不能这么写:
struct Point {mut x: i32,y: i32,
}
*///此外,结构体的域对其所在模块 (mod) 之外默认是私有的,可以使用pub关键字将其设置成公开。mod graph {pub struct Point {pub x:i32,y:i32,z:i32,}pub fn new_point()->Point{Point{x:0,y:0,z:0}}
}
fn main() {let p = graph::new_point();println!("{}",p.x);
}

12.结构体方法

struct Point { x: i32, y: i32 }
impl Point{fn origin() -> Point{ //不含self的关联方法为静态方法Point{x:0,y:0}}fn area(&self) -> i32 {let a = self.x;let b = self.y;a*b}fn set(& mut self, x:i32,y:i32) {self.x = x;self.y = y;}
}
fn main() {let mut point = Point::origin();point.set(10, 10);println!("{}",point.area() )
}

13.泛型

fn main() {let p :Pair<i64> = Pair{ first:1, second:2};println!(" {}, {}",p.first,p.second);
}
struct Pair<T> {    first:T,second:T,
}
#[allow(dead_code)]
fn swap<T>(pair : Pair<T>) -> Pair<T> {let Pair{first,second} = pair;Pair{first:second, second:first}
}
  • 泛型应用如下
use std::collections::VecDeque;
type BinNodeEnum<K,V> = Option<Box<BinNode<K,V>>>;
#[derive(Debug)]//二叉树
pub struct BinNode<K,V> where K: std::cmp::PartialOrd+ std::fmt::Debug{ //节点left : BinNodeEnum<K,V>,right : BinNodeEnum<K,V>,pub key : K,pub value : V,
}impl<K,V> BinNode<K,V> where K:std::cmp::PartialOrd + std::fmt::Debug {pub fn new(key1: K, value1: V) -> BinNode<K,V> {BinNode{left:None,right:None,key: key1,value:value1,}}//果然是递归的好写, 先写完递归的, 然后按照 递归->非递归转为非递归代码pub fn insert_recursive(&mut self,k:K,v:V) {if self.key < k {if let Some(ref mut right) = self.right {right.insert_recursive(k,v);}else {self.right = Some(Box::new(BinNode::new(k, v))); }}else {if let Some(ref mut left) = self.left {left.insert_recursive(k,v);}else {self.left = Some(Box::new(BinNode::new(k, v))); }}}//仅仅是打印fn visit_node(&self) {println!("key = {:#?}",self.key);}//遍历树//前序pub fn pre_order(&mut self) {self.visit_node();if let Some(ref mut l) = self.left{l.pre_order();}if let Some(ref mut r) = self.right{r.pre_order();}}//BFS - nonrecurpub fn bfs(&mut self) {let mut queue = VecDeque::new(); //标准库的容器queue.push_back(self);while let Some(node) = queue.pop_front() {node.visit_node();if let Some(ref mut l) = node.left{queue.push_back(l);}if let Some(ref mut r) = node.right{queue.push_back(r);}}}
}

更多推荐

rust笔记1

本文发布于:2023-07-28 16:29:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250232.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:笔记   rust

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!