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);
    }
    
    
  • 相关阅读:
    Props VS State
    Component VS PureComponent
    Webpack loaders
    近期需要学习的技术
    jQuery源码解读三选择器
    jQuery源码解读二(apply和call)
    jQuery源码解读一
    Web语义化
    如何用python语言撸出图表系统
    抓取android系统日志_记录一次定位app闪退故障
  • 原文地址:https://www.cnblogs.com/cutepig/p/12685126.html
Copyright © 2011-2022 走看看