面向云技术架构 - 痴者工良

  • 首页
  • 资源导航
    • 值得收藏的网站导航
    • 本站文章导航
    • 资源下载
  • 教程文档
    • kubernetes 教程
    • 多线程和异步
    • 动态编程-反射、特性、AOP
    • 表达式树
  • 隐私政策
无虑
青山一片云雾,心安即归处,山泉水洗去来时的尘土。
听风吹过松竹,自在即归处,借一壶清茶伴日出。
  1. 首页
  2. 编程语言
  3. rust
  4. 正文

Rust:Providing a default implementation,how use to Default::default()

2020年11月23日 1216点热度 0人点赞 0条评论
内容纲要

Providing a default implementation

Often, when dealing with structures that represent configurations, you don't care about certain values and just want to silently assign them a standard value.

通常,当处理表示配置的结构时,你并不关心某些值,只想为其默默分配一个标准值。

Rust 使用 Default::default(); 为类型分配一个默认值,相当于 C# 的 default、default({type})。

Rust 中几乎每个原始类型都有一个默认值。

Default::default() 使用方法如下:

    // There's a default value for nearly every primitive type
    let foo: i32 = Default::default();
    println!("foo: {}", foo); // Prints "foo: 0"

结构体(struct)要设置默认值,需要带上 #[derive(Default)] 特性。

#[derive(Default)]
struct PizzaConfig {
    wants_cheese: bool,
    number_of_olives: i32,
    special_message: String,
}

... ...

    // A struct that derives from Default can be initialized like this
    let pizza: PizzaConfig = Default::default();

    // Prints "wants_cheese: false
    println!("wants_cheese: {}", pizza.wants_cheese);

    // Prints "number_of_olives: 0"
    println!("number_of_olives: {}", pizza.number_of_olives);

    // Prints "special_message: "
    println!("special message: {}", pizza.special_message);

结构体设置默认值

rust 枚举默认栈需要实现 Default 接口:

// You can implement default easily for your own types
enum CrustType {
    Thin,
    Thick,
}
impl Default for CrustType {
    fn default() -> CrustType {
        CrustType::Thin
    }
}
    let _enum:CrustType=Default::default();
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: default how implementation providing rust
最后更新:2021年2月21日

痴者工良

高级程序员劝退师

点赞
< 上一篇
下一篇 >

文章评论

取消回复
You must enable javascript to see captcha here!
目录导航

COPYRIGHT © 2022 whuanle.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

粤ICP备18051778号

粤公网安备 44030902003257号