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);
}

Powered by Jekyll and Theme by solid

本站总访问量