#bro #options #resources #initialization #possibly #ption #b-option

broption

当你需要更多 bro 的功能时使用

2 个版本

0.1.1 2023 年 4 月 14 日
0.1.0 2023 年 4 月 13 日

#3 in #possibly

MIT/Apache

6KB
72

Broption

当你需要更多 bro 的功能时使用。


lib.rs:

品牌化的 Option。当你需要 bro 的功能时使用。

可能不安全。设计用于与 selfref 一起使用。

示例

use broption::BOption;

// define a resource that needs a separate initialization step.
struct Foo<'bro> {
  name: BOption<'bro, Box<str>>,
}

// define a context wrapper for our resource.
struct Ctx;
impl broption::Wrapper for Ctx {
  type Kind<'bro> = Foo<'bro>;
}

// create an "initialization context".
let initialized = BOption::factory::<Ctx, _>(|factory| {
  // create an uninitialized resource.
  let mut maybeinit = Foo {
    name: factory.new_none(),
  };
  // initialize the resource.
  factory.init(&mut maybeinit.name, Box::from("hello"));
  // return the hopefully-initialized resource.
  maybeinit
});
// use the initialized resource
assert_eq!(&**initialized.name, "hello");

未能正确初始化资源导致恐慌

use broption::BOption;

// define a resource that needs a separate initialization step.
struct Foo<'bro> {
  name: BOption<'bro, Box<str>>,
}

// define a context wrapper for our resource.
struct Ctx;
impl broption::Wrapper for Ctx {
  type Kind<'bro> = Foo<'bro>;
}

// create an "initialization context".
let initialized = BOption::factory::<Ctx, _>(|factory| {
  // create an uninitialized resource.
  let mut maybeinit = Foo {
    name: factory.new_none(),
  };
  // return the uninitialized resource.
  maybeinit
});

无运行时依赖