#声明式 #编程 #Makefile #依赖 #辅助 #先决条件

目标

一些辅助工具,帮助您开始 Rust 中的声明式编程

2 个版本

使用旧的 Rust 2015

0.1.1 2018 年 5 月 12 日
0.1.0 2018 年 5 月 12 日

#1472Rust 模式

MIT 许可证

9KB
112

目标

一些辅助工具,帮助您开始 Rust 中的声明式编程

用法

此软件包定义了 3 个宏

  • capture!($ident):注册基本需求
  • target!($ident($args) -> $ty = $expre):定义一个目标,它使用固定配方从先决条件构建某些内容
  • build!($ident: $ty, $builder):基于给定状态构建目标

示例

让我们构建一个 Dashboard 结构体,其中包含一个用户欢迎消息。

我们将基本需求定义为 State 结构体,其中包含一个会话标识符。

为了构建仪表板,我们需要实际的消息和已登录的用户。这些定义为两个独立且依赖的目标。

#[macro_use]
extern crate targets;

use targets::Target;
use targets::Builder;

pub struct State {
    logged_in_id: i32,
    message_of_the_day: String,
}
pub struct User {
    id: i32,
    username: String,
}
pub struct Dashboard {
    message: String,
}

fn main() {
    // register `state` which is the base requisite
    capture!(state);

    // declare a target which depends on `state`
    target!(fn user(state: State) -> User = {
        User {
            id: state.logged_in_id, // you may want to get the user from a database
            username: "otto".to_string()
        }
    });

    // declare a target which depends on another target
    target!(fn message(user: User) -> String = {
        String::from(format!("Welcome {} (user_id {})", user.username, user.id))
    });

    // a target can depend on as many other targets
    target!(fn dashboard(message: String, state: State) -> Dashboard = {
        Dashboard {
            message: format!("{} {}", state.message_of_the_day, message),
        }
    });

    // Let's run our build script, set up the state:
    let my_state = State {
        logged_in_id: 8,
        message_of_the_day: String::from("Good morning!")
    };
    let mut my_builder = Builder::new(Box::new(my_state));
    // Build the dashboard:
    {
        let my_dashboard = build!(dashboard: Dashboard, my_builder);
        assert_eq!("Good morning! Welcome otto (user_id 8)", my_dashboard.message);
    }
    // Build another target from the same initial state
    // Since it has already been built as part of the dashboard, it won't rebuild anything
    {
        let my_user = build!(user: User, my_builder);
        assert_eq!("otto", my_user.username);
    }

    // Use our dependency graph to build another item
    let my_state = State {
        logged_in_id: 12,
        message_of_the_day: String::from("It's Wednesday!")
    };
    let mut my_builder = Builder::new(Box::new(my_state));
    {
        let my_dashboard = build!(dashboard: Dashboard, my_builder);
        assert_eq!("It's Wednesday! Welcome otto (user_id 12)", my_dashboard.message);
    }
}

无运行时依赖项