在Rust中管理依赖项有哪些方法?

时间:2019-04-28 23:20:44

标签: architecture rust dependency-management

我对Rust还是陌生的,正在尝试把我的头放在依赖管理和人们如何布置项目上。

我创建了一个小示例,并想知道其他开发人员如何解决此问题。您是否会增加生命周期并借用,以不同方式拆分代码,为每个依赖项实例化Counter实例,是否还要做其他事情?

结构相当简单,但是假设Counter是HTTP客户端实例,而IncrementDecrement是使用该实例的服务。还请注意,随着项目的成熟,我们可能会传递数十个依赖项。

// core/src/lib.rs
///! Main library
use counter;
use decrement;
use increment;

/// Register modules
pub fn create_app() {
    let mut counter = counter::Counter::new();

    // We can't share ownership so this will not compile
    let mut increment = increment::Increment::new(counter);
    let mut decrement = decrement::Decrement::new(counter);

    increment.increment_by(10);
    decrement.decrement_by(10);
}
// counter/src/lib.rs
pub struct Counter {
    count: i32,
}

impl Counter {
    pub fn new() -> Counter {
        Counter {
            count: 0
        }
    }

    pub fn get_count(&self) -> i32 {
        self.count
    }

    pub fn increment(&mut self) -> i32 {
        self.count += 1;
        self.get_count()
    }

    pub fn decrement(&mut self) -> i32 {
        self.count -= 1;
        self.get_count()
    }
}
// increment/src/lib.rs
use counter;

pub struct Increment {
    counter: counter::Counter,
}

impl Increment {
    pub fn new(counter: counter::Counter) -> Increment {
        Increment { counter }
    }
    pub fn increment_by(&mut self, amount: i32) {
        for _ in 0..amount {
            self.counter.increment();
        }
    }
}
// decrement/src/lib.rs
use counter;

pub struct Decrement {
    counter: counter::Counter,
}

impl Decrement {
    pub fn new(counter: counter::Counter) -> Decrement {
        Decrement { counter }
    }

    pub fn decrement_by(&mut self, amount: i32) {
        for _ in 0..amount {
            self.counter.decrement();
        }
    }
}

0 个答案:

没有答案