I think Rust might currently be missing a convenient way to allow the addition of functionality to existing code, especially library code. As a library writer you currently have two options: make something (attribute/function) public, which allows use by others and makes it part of the API, or make it private, which completely hides it away, inaccessible, for everyone. There is no option to say something like “this is not the public API, but you can use it if you know what you’re doing.” C++ has this in the form of protected members, Ruby has this in the form of extending classes (either directly or through modules).
The current status quo generally leaves several options: 1) try to use the public API, which might be impossible at worst or sometimes horribly slow at best 2) modify the library, which is not very portable, especially in the case of the standard library 3) reimplement the original code, which seems silly if the original code is good.
How could this be properly supported in Rust?
In case you’re still wondering what I’m talking about, here’s an example of something someone might want to do that is currently not possible:
use std::intrinsics::cttz32;
use std::collections::{Bitv,BitvSet};
pub trait LowestBit
{
fn lowest_bit(&self) -> Option<usize>;
}
impl LowestBit for Bitv
{
fn lowest_bit(&self) -> Option<usize>
{
// error: field `storage` of struct `collections::bit::Bitv` is private
for (idx,&word) in self.storage.iter().enumerate()
{
if (word==0) { continue }
return Some(idx*32+(unsafe {cttz32(word) as usize}));
}
return None;
}
}
fn main() {
let mut v=BitvSet::new();
v.insert(1242);
println!("{}",v.get_ref().lowest_bit().unwrap());
}
Yes, one can implement lowest_bit a different way, but at the expense of performance.
(You might have seen this on GitHub issue tracker - I realize the bug tracker is not an appropriate place to discuss this but this forum is actually not linked from the rust-lang.org homepage)