Rust の re-exporting 小技


外部クレートを改造しながら自分のクレートにモジュールとして埋め込みます。

3 通りの re-export

thunderdome を 3 通りの方法で re-export します。

1. pub use external_crate;

rlbox/src/tmp.rs
//! Tmp

pub use thunderdome;
// or:
// pub extern crate thunderdome;

クリックすると、外部クレートのドキュメントにジャンプしました:

2. #[doc(inline)] pub use external_crate

Rust by Example の meta の項に載っている #[doc(inline)] を試します。

rlbox/src/tmp.rs
//! Tmp

// 実は docstring の頭に自分の文章を追加できる:
/// [`thunderdome`] re-exported as `generational_aerna`
///
///
#[doc(inline)]
pub use thunderdome as generational_arena;

// as 以下はあってもなくてもいい

クリックすると、直下のモジュールとして表示されました:

また、 docstring に自分が書いた文章 (thunderdome re-exported ..) が追加されていることに注目してください。

3. pub use external_crate::*

rlbox/src/tmp.rs
//! Tmp

pub mod arena {
    /*!
    [`thunderdome`] re-exported. Note that [`Index`] is not reference-counted.
    */

    pub use thunderdome::*;
}

クリックすると:

thunderdome の docstring を消去できました。 Docstring 中の thunderdome をクリックすると、オリジナルのドキュメントを見ることができます。

僕が書いた文章 (docstring) がおかしいのは許してください……。

活用例: soloud-rs を改造しながら re-export

snow2d/src/audio.rs
/*!
[`soloud-rs`] re-exported with additional types and [`snow2d::asset`] integration

[SoLoud] is an easy to use, free, portable c/c++ audio engine for games.
*/

pub use soloud::{audio as src, filter, prelude, Handle, Soloud as AudioDrop};

use std::{
    ops::{Deref, DerefMut},
    rc::Rc,
};

/// Reference-counted ownership of [`AudioDrop`]
#[derive(Debug, Clone)]
pub struct Audio {
    inner: Rc<AudioDrop>,
}

impl Audio { /* ~~ */ }
impl Deref for Audio { /* ~~ */ }
impl DerefMut for Audio { /* ~~ */

pub mod asset {
    //! [`snow2d::asset`](crate::asset) integration

    // ~~
}

オリジナルのドキュメント と比較しても分かる通り、型の名前を変えたり、一部の re-export を削除して、また Audio 型と asset モジュールを追加しています。