Rust programming video tutorial (Advanced) – 027_ 1 advanced features


Video address

Headline address:…
Station B address:

Source address

GitHub address:…

Explanation content

1. Type alias

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

Note: in the example, kilmeters is a synonym for I32. Values of the kilometers type are treated exactly as I32 types.
The main purpose of type aliases is to reduce duplication.

(1) Consider the following types:

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

Such as code:

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-- 

Use alias, code:

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) Consider the following examples:

use std::io::Error; // The STD:: IO:: error structure in the standard library represents all possible I / O errors 
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>; 

Add the following type alias declaration:

type Result<T> = std::result::Result<T, std::io::Error>;// STD:: IO:: error is placed in result < T, E >

The code can become:

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<()>; 

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]