• 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);
    }
    
    
  • 相关阅读:
    OnClick方法与Click事件
    词法,语法,语义
    静态成员与实例成员
    依赖属性 DependencyProperty
    依赖,关联,聚合,合成
    数据可视化
    ref 与out
    理解TCP为什么需要进行三次握手(白话)
    禁止访问网站中所有的动态页面
    linux 重命名文件和文件夹
  • 原文地址:https://www.cnblogs.com/cutepig/p/12685126.html
Copyright © 2020-2023  润新知