Trait with private items
⚓ Rust 📅 2025-09-26 👤 surdeus 👁️ 11Hi,
I would like to make a trait some items private and some public. I have considered to use sealed super trait, but in my case the private items depend on public ones, so it didn't work (also, I think it would not make private items inaccessible).
I would like something like this:
// The trait should be visible by user and usable in bounds.
// It cannot be implemented by user, but that's fine.
pub trait MyTrait {
// This type should be public
type Item;
// This type should be private, it is an implementation detail,
// completely invisible to user, it should not be a breaking
// change to change or remove this.
type Iter: Iterator<Item = Self::Item>;
// This function should be private, it is an implementation detail,
// completely invisible to user, it should not be a breaking
// change to change or remove this.
fn get_item(&mut self) -> Self::Item;
}
// There are functions like this in my library
pub fn do_something<T: MyTrait>(value: T) -> T::Item {
todo!()
}
// ... and some implementations of MyTrait
struct Foo;
impl MyTrait for Foo { /* ... */ }
I am currently considering two approaches:
- Just
#[doc(hidden)]the private items (and maybe add extra unnameable-typed argument to functions). - Keep them public and document them (maybe adding a "but pretend you do not see this" note).
I don't like any of them. Is there anything better?
3 posts - 3 participants
🏷️ Rust_feed