#macro-derive #field #initialization #self-referential #borrow #incrstruct #incr-struct

incrstruct_derive

IncrStruct derive宏,请参阅incrstruct包

4个版本

新增 0.1.3 2024年8月13日
0.1.2 2024年8月13日
0.1.1 2024年8月12日
0.1.0 2024年8月12日

25#self-referential 中排名

Download history 445/week @ 2024-08-10

每月下载量 445
用于 incrstruct

MIT 协议

17KB
322

增量结构

crates.io docs.rs GitHub last commit

一个用于使用两阶段初始化构建自引用结构的Rust包。

示例

use std::cell::{Ref, RefCell};
use incrstruct::IncrStruct;

#[derive(IncrStruct)]
struct AStruct<'a> {
    #[borrows(b)]             // Borrowing from a tail field
    c: &'a Ref<'a, i32>,      // is possible.

    #[borrows(a)]             // You can only borrow from fields that
    b: Ref<'a, i32>,          // come after the current field.

    a: RefCell<i32>,          // A head field. Since you can only borrow
                              // immutable references, RefCell is useful.

    #[header]                 // The required header field.
    hdr: incrstruct::Header,  // The name is arbitrary.
}

// The AStructInit trait is generated by the derive macro and
// ensures the contract between the incrstruct library code and
// the user provided code matches. The functions are invoked in
// reverse field declaration order.
impl<'a> AStructInit<'a> for AStruct<'a> {
    fn init_field_c(b: &'a Ref<'a, i32>) -> &'a Ref<'a, i32> {
        b
    }

    fn init_field_b(a: &'a RefCell<i32>) -> Ref<'a, i32> {
        a.borrow()
    }
}

// Only head fields are provided to the generated `new_X` functions.
let my_a = AStruct::new_box(RefCell::new(42));

assert_eq!(*my_a.a.borrow(), *my_a.b);

有关更多信息,请参阅文档

依赖项

~285–740KB
~18K SLoC