3.tipo palabra clave.rs

/*
你可以使用 type 关键字声明另一类型的别名(用法和C++一样一样的)
类型别名:type aliases
type Name = String;

type 也可以用来声明trait的关联类型,详细请看“特性trait”章节

更多详细信息请看:
https://github.com/rooat/RustLearn/blob/master/src/ch19-04-advanced-types.md
*/

fn test_1() {
     type Name = String;
     let x: Name = "Hello".to_string();
     println!("{}", x);
}

//但是请注意,这是一个别名,不完全是一个新类型。换句话说,因为 Rust 是强类型的,所以你不能比较两个不同类型
fn test_2() {
     type Name1 = i32;
     type Name2 = i32;
     let x1: Name1 = 36;
     let x2: Name2 = 34;
     if x1 == x2 {
          println!("same value");
     } else {
          println!("not same value");
     }
}

/*
你还可以使用泛型类型别名:
use std::result;
enum ConcreteError {
Foo,
Bar,
}
type Result<T> = result::Result<T, ConcreteError>;
这将创建一个 Result 类型的专门的版本 ,它总是有一个针对 Result< T E > 的 E 部分的 ConcreteError 。
这常被用在标准库来为每一部分创建自定义错误。例如,io::Result 。
*/
fn test_3() {
     use std::result;
     enum ConcreteError {
          Foo,
          Bar,
     }
     type Result<T> = result::Result<T, ConcreteError>;
}

fn main() {
     test_1();
     test_2();
     test_3();
}

 

Supongo que te gusta

Origin blog.csdn.net/liujiayu2/article/details/114364631
Recomendado
Clasificación