Rust 程式設計視訊教程(進階)——027_1 高階特性

linghuyichong發表於2020-02-22

頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

github地址:https://github.com/anonymousGiga/learn_rus...

1、型別別名
例子:

type Kilometers = i32;
let x: i32 = 5; 
let y: Kilometers = 5; 
println!("x + y = {}", x + y);

說明:例子中Kilmeters 是i32的同義詞。Kilometers 型別的值完全當作i32型別來對待。
型別別名的主要用途是減少重複。

(1)考慮如下型別:

Box<dyn Fn() + Send + 'static>

如程式碼:

let f: Box<dyn Fn() + Send + 'static> = Box::new(|| println!("hi")); 
fn takes_long_type(f: Box<dyn Fn() + Send + 'static>) { 
    // --snip-- 
} 
fn returns_long_type() -> Box<dyn Fn() + Send + 'static> { 
    // --snip-- 
}

使用別名,程式碼:

type Thunk = Box<dyn Fn() + Send + 'static>; 
let f: Thunk = Box::new(|| println!("hi")); 
fn takes_long_type(f: Thunk) { 
    // --snip--
} 
fn returns_long_type() -> Thunk { 
    // --snip-- 
}

(2)考慮如下例子:

use std::io::Error; //標準庫中的std::io::Error結構體代表了所有可能的I/O錯誤 
use std::fmt; 
pub trait Write { 
    fn write(&mut self, buf: &[u8]) -> Result<usize, Error>; 
    fn flush(&mut self) -> Result<(), Error>; 
    fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>;
    fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>; 
}

加上如下型別別名宣告:

type Result<T> = std::result::Result<T, std::io::Error>;//result<T, E> 中 E 放入了 std::io::Error

程式碼就可以變成:

pub trait Write { 
    fn write(&mut self, buf: &[u8]) -> Result<usize>; 
    fn flush(&mut self) -> Result<()>; 
    fn write_all(&mut self, buf: &[u8]) -> Result<()>; 
    fn write_fmt(&mut self, fmt: Arguments) -> Result<()>; 
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

令狐一衝

相關文章