【问题标题】:Returning a type, not an instance返回一个类型,而不是一个实例
【发布时间】:2016-01-21 01:52:38
【问题描述】:

Rust 中是否有一种方法可以从函数返回实现特定特征的类型(我不想要实例,而是类型)。像这样的东西(在当前形式下不起作用):

trait MyTrait {
    fn sum(&self, val: i64) -> i64;
}

#[derive(Debug)]
struct X {
    x: i64,
}

impl MyTrait for X {
    fn sum(&self, val: i64) -> i64 {
        self.x + 2 * val
    }
}

#[derive(Debug)]
struct Y {
    x: i64,
}

impl MyTrait for Y {
    fn sum(&self, val: i64) -> i64 {
        self.x + 3 * val
    }
}

fn from_name(name: &str) -> MyTrait {
    match name {
        "X" => X,
        "Y" => Y,
        _ => panic!("Unknown name")
    }
}

fn main() {
    let x = X{x: 21};
    let y = Y{x: 42};

    // This does not work, it is just to show the idea
    let z = from_name("X"){x: 10};

    println!("x {:?}", x.sum(3));
    println!("y {:?}", y.sum(3));
    println!("z {:?}", z.sum(3));
}

【问题讨论】:

    标签: types return rust traits


    【解决方案1】:

    与您所要求的最接近的是工厂函数:

    fn from_name(name: &str) -> Box<Fn(i64) -> Box<MyTrait>> {
        match name {
            "X" => Box::new(|x| Box::new(X{x: x})),
            "Y" => Box::new(|x| Box::new(Y{x: x})),
            _ => panic!("Unknown name"),
        }
    }
    
    fn example() -> i64 {
        let factory = from_name("X");
        let z = factory(10);
        z.sum(10)
    }
    

    from_name 返回一个返回对象的函数。

    【讨论】:

    • 注意,你可以做到这一点而不必有一个闭包,甚至可能不必有一个 Box&lt;MyTrait&gt; 特征对象,通过枚举例如enum Maker { X, Y }from_name 返回,其方法类似于fn make(&amp;self, i64) -&gt; Value,其中enum Value { X(X), Y(Y) }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多