相关疑难解决方法(0)

是否允许多态变量?

我有各种结构,都实现相同的特征.我想在某些条件下进行分支,在运行时决定实例化哪些结构.然后,无论我遵循哪个分支,我都想从该特征中调用方法.

这可能在Rust吗?我希望实现类似下面的内容(不编译):

trait Barks {
    fn bark(&self);
}

struct Dog;

impl Barks for Dog {
    fn bark(&self) {
        println!("Yip.");
    }
}

struct Wolf;

impl Barks for Wolf {
    fn bark(&self) {
        println!("WOOF!");
    }
}

fn main() {
    let animal: Barks;
    if 1 == 2 {
        animal = Dog;
    } else {
        animal = Wolf;
    }
    animal.bark();
}
Run Code Online (Sandbox Code Playgroud)

rust

14
推荐指数
3
解决办法
655
查看次数

是否有可能在Rust中返回借用或拥有的类型?

在下面的代码中,如何返回引用floor而不是新对象?是否可以让函数返回借用的引用或拥有的值?

extern crate num; // 0.2.0

use num::bigint::BigInt;

fn cal(a: BigInt, b: BigInt, floor: &BigInt) -> BigInt {
    let c: BigInt = a - b;
    if c.ge(floor) {
        c
    } else {
        floor.clone()
    }
}
Run Code Online (Sandbox Code Playgroud)

ownership rust

11
推荐指数
1
解决办法
1138
查看次数

标签 统计

rust ×2

ownership ×1