zoukankan      html  css  js  c++  java
  • rust: 默认初始化,函数重载

    rust: 默认初始化,函数重载

    默认初始化

    如下

    pub struct Foo {
        bar: String,
        baz: i32,
        quux: bool,
    }
    
    impl Default for Foo {
        fn default() -> Self {
            Foo {
                bar: "".to_string(),
                baz: 0,
                quux: false,
            }
        }
    }
    
    impl Foo {
        pub fn new() -> Self {
            Foo {
                ..Default::default()
            }
        }
    
        fn new_str(x: String) -> Self {
            Foo {
                bar: x,
                ..Default::default()
            }
        }
        fn new_i32(x: i32) -> Self {
            Foo {
                baz: x,
                ..Default::default()
            }
        }
        fn new_bool(x: bool) -> Self {
            Foo {
                quux: x,
                ..Default::default()
            }
        }
    }
    
    #[test]
    fn name() {
        let a = Foo::new_i32(1);
    }
    
    

    函数重载

    rust本身不支持函数重载,但是可以用泛型trait实现类似于重载的效果

    如下,

    pub trait With<T> {
        fn with(value: T) -> Self;
    }
    
    struct Foo {
        bar: String,
        baz: i32,
        quux: bool,
    }
    
    impl Default for Foo {
        fn default() -> Self {
            Foo {
                bar: "".to_string(),
                baz: 0,
                quux: false,
            }
        }
    }
    
    impl Foo {
        fn new() -> Self {
            Foo {
                ..Default::default()
            }
        }
    }
    
    impl With<String> for Foo {
        fn with(x: String) -> Self {
            Foo {
                bar: x,
                ..Default::default()
            }
        }
    }
    
    impl With<i32> for Foo {
        fn with(x: i32) -> Self {
            Foo {
                baz: x,
                ..Default::default()
            }
        }
    }
    
    impl With<bool> for Foo {
        fn with(x: bool) -> Self {
            Foo {
                quux: x,
                ..Default::default()
            }
        }
    }
    
    #[test]
    fn name() {
        let a = Foo::with(1);
    }
    
    
  • 相关阅读:
    一、JDBC操作
    十五、时间日期类
    十四、字符串详解
    源文件
    十六、·实现显示所有雇员
    十五、抽象出基础接口
    十四、增加EmployeeService实现用户添加
    十三、解决懒加载
    python __new__以及__init__
    Python的getattr(),setattr(),delattr(),hasattr()及类内建__getattr__应用
  • 原文地址:https://www.cnblogs.com/cutepig/p/12685126.html
Copyright © 2011-2022 走看看