Rust的入门篇(中)
这是接上面一篇rust入门篇(上)文章
22. 包管理一
rust
mod nation {
pub mod government {
pub fn govern() {}
}
mod congress {
pub fn legislate() {}
}
mod court {
fn judicial() {
super::congress::legislate();
}
}
}
fn main() {
nation::government::govern();
}
23. 包管理二
rust
mod back_of_house{
pub struct Breakfast{
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast{
pub fn summer(toast: &str)->Breakfast{
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peaches"),
}
}
}
}
pub fn eat_at_restaurant(){
let mut meal = back_of_house::Breakfast::summer("Rye");
meal.toast = String::from("Wheat");
println!("I'd like {} toast please", meal.toast);
}
fn main() {
eat_at_restaurant();
}
24. 包管理三
rust
use std::fs::Permissions;
mod SomeModule{
pub enum Person{
King {
name: String
},
Queen
}
}
fn main() {
let person = SomeModule::Person::King {
name: String::from("Blue")
};
match person {
SomeModule::Person::King { name } =>{
println!("{}", name);
}
_=>{}
}
// Blue
}
25. 包管理四 导入包
second_modules.rs
rust
pub fn message()->String{
String::from("this is the 2nd module")
}
rust
// 学习如何导入一个外来的模块
mod second_module;
fn main(){
println!("This is the main module");
println!("{}", second_module::message())
}
// This is the main module
// this is the 2nd module
27. 使用use关键字引入包内的函数
rust
mod nation{
pub mod government{
pub fn govern(){
println!("hello world");
}
}
}
// use关键字的使用
use crate::nation::government::govern;
fn main(){
govern();
}
28. 泛型编程一
模板编程
rust
fn max<T>(array: &[T]) -> T {
let mut max_index = 0;
let mut i = 1;
while i < array.len() {
if array[i] > array[max_index] {
max_index = i;
}
i += 1;
}
array[max_index]
}
fn main(){
let a = [2, 4, 6, 3, 1];
println!("max={}", max(&a));
}
28. use as
rust
mod nation{
pub mod government{
pub fn govern(){println!("nation govern")}
}
pub fn govern(){println!("govern")}
}
use crate::nation::government::govern as nation_govern;
use crate::nation::govern;
fn main(){
nation_govern(); // nation govern3
govern(); // govern
}
29. use-pub
rust
mod nation{
pub mod government{
pub fn govern(){println!("nation govern")}
}
pub use government::govern;
}
use crate::nation::government::govern as nation_govern;
use crate::nation::govern;
fn main(){
nation_govern(); // nation govern3
govern(); // govern
}
30. 第三方库
rust
use std::f64::consts::PI;
fn main(){
println!("{}", (PI*3.0/2.0).sin());
}
31. exception1
rust
fn main(){
// panic!("error occured");
println!("hello, rust");
}
32. exception2
rust
use std::fs::File;
// 异常处理1
fn main(){
let f = File::open("hello.txt");
match f{
Ok(file) => {
println!("File opened successfully.");
}
Err(err)=>{
println!("Failed to open file.");
}
}
}
33. exception3
rust
use std::fs::File;
// 异常处理2
fn main(){
let f = File::open("hello.txt");
if let Ok(file) = f{
println!("File opened succefully")
} else {
println!("fail to open.");
}
}
34. exception4
rust
use std::fs::File;
fn main(){
// 可恢复错误按不可恢复错误处理
// 不发送错误信息
// let f1 = File::open("hello.txt").unwrap();
// 发送错误信息
// let f2 = File::open("hello.txt").expect("Failed to open");
// 啥也没做,不知道是否错误
let f2 = File::open("hello.txt");
}
35. exception5
rust
// 异常的传递
fn f(i:i32)->Result<i32, bool>{
if i>=0 {
Ok(i)
}
else {
Err(false)
}
}
fn g(i:i32)->Result<i32, bool>{
// ? 符的实际作用是将 Result 类非异常的值直接取出,如果有异常就将异
// 常 Result 返回出去。所以,? 符仅用于返回值类型为 Result<T, E> 的函数,
// 其中 E 类型必须和 ? 所处理的 Result 的 E 类型一致
let t = f(i)?;
Ok(t)
}
fn main(){
let r = g(10000);
if let Ok(v) = r{
println!("Ok: g(10000) = {}", v);
} else {
println!("Err");
}
}
36. exception6
rust
use std::io;
use std::io::Read;
use std::fs::File;
// 读取文件,并捕获文件不存在的异常
fn read_text_from_file(path: &str) -> Result<String, io::Error> {
let mut f = File::open(path)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
fn main() {
let str_file = read_text_from_file("d://hello.txt");
match str_file {
Ok(s) => println!("{}", s),
Err(e) => {
// kind 方法
match e.kind(){
io::ErrorKind::NotFound=>{
println!("no such file");
},
_=>{
println!("cannot read file.");
}
}
}
}
}
37. 泛型编程1
rust
// 非泛型的情况,传入的数据类型只能是i32
fn max(array:&[i32])->i32{
let mut max_index = 0;
let mut i = 1;
while i < array.len(){
if array[i] > array[max_index]{
max_index = i;
}
i += 1;
}
array[max_index]
}
fn main(){
let a = [2, 4, 6, 3, 1];
println!("max={}", max(&a));
}
38. 泛型编程2
rust
// 枚举+泛型编程
struct Point<T>{
x: T,
y: T
}
fn main(){
let p1 = Point {x:1, y:2};
let p2 = Point {x: 1.0, y: 2.0};
// p1.x=1, p1.y=2
println!("p1.x={}, p1.y={}", p1.x, p1.y);
// 下面错误的,不能使用2个不同的类型
// let p3 = Point {x: 1, y: 2.0};
}
39. 泛型编程3
rust
// 枚举+泛型编程
struct Point<T1, T2>{
x: T1,
y: T2
}
fn main(){
// 使用2个不同的类型
let p3 = Point {x: 1, y: 2.0};
println!("p3.x={}, p3.y={}", p3.x, p3.y);
}
40. 泛型编程4
在结构体定义泛型方法
rust
struct Point<T>{
x: T,
y: T
}
// 结构体与枚举类定义泛型方法
impl<T> Point<T> {
fn x(&self)->&T{
&self.x
}
}
fn main(){
let p = Point{x:1, y:2};
println!("p.x = {}", p.x());
}
41. 泛型编程5
特性trait的定义与实施
rust
trait Descriptive {
fn describe(&self)->String{
String::from("[Object]")
}
}
struct Person{
name: String,
age: u8
}
impl Descriptive for Person {
fn describe(&self)->String {
format!("{} {}", self.name, self.age)
}
}
fn main(){
let cali = Person{
name: String::from("Cali"),
age: 24
};
println!("{}", cali.describe());
}
42. 泛型编程6
rust
// 特性(trait)概念接近于 Java 中的接口(Interface),但两者不完全相同。特性与接
// 口相同的地方在于它们都是一种行为规范,可以用于标识哪些类有哪些方法。
trait Descriptive {
fn describe(&self)->String{
String::from("[Object]")
}
}
struct Person{
name: String,
age: u8
}
impl Descriptive for Person {
fn describe(&self)->String {
format!("{} {}", self.name, self.age)
}
}
fn main(){
let cali = Person{
name: String::from("Cali"),
age: 24
};
println!("{}", cali.describe());
}
43. 泛型编程7
综合例子
rust
// 特性例子简介
// 定义特性
trait Comparable {
fn compare(&self, object: &Self)->i8;
}
// 实现特性 并 绑定到 f64类型下
impl Comparable for f64 {
fn compare(&self, object: &f64)->i8{
if &self > &object{1}
else if &self == &object{0}
else {-1}
}
}
fn max<T: Comparable>(array: &[T])->&T{
let mut max_index = 0;
let mut i = 1;
while i < array.len(){
if array[i].compare(&array[max_index])>0{
max_index = i;
}
i += 1;
}
&array[max_index]
}
fn main(){
// 默认arr的类型是[f64; 5]
let arr = [1.0, 3.0, 5.0, 4.0, 2.0];
println!("maximum of arr is {}", max(&arr));
}
44. 泛型编程8
特征做为返回值出现
rust
// 特性作为返回值
trait Descriptive {
fn describe(&self)->String{
String::from("[Object]")
}
}
impl Descriptive for Person {
fn describe(&self)->String {
format!("{} {}", self.name, self.age)
}
}
struct Person{
name: String,
age: u8
}
// 特征作为返回值出现
fn person() -> impl Descriptive {
Person {
name: String::from("Cali"),
age: 24
}
}
fn main(){
let p = person();
println!("{}", p.describe());
}