How use nightly feature on a library and it possible if everything else is on stable and only a lib is nightly feature

How do I use a nightly feature
I already install cargo +nightly so how I use it. It errors saying E0554

E0554 means that you are not actually using the nightly compiler. cargo +nightly build will never give E0554.

Okay but would I need build whole binary with +nightly or can I build the most file in stable whereas the lib will build +nightly or no

Yes, you'll need to build the whole program with the nightly toolchain.

1 Like

Ok

When I ran across this, I just copied the std's implementation into my project (the function in question was slice::element_offset).

Can you provide more details please?

  1. Look up the function I want to use. slice::element_offset for instance.
  2. Jump to its code from Rust documentation.
    pub fn element_offset(&self, element: &T) -> Option<usize> {
        if T::IS_ZST {
            panic!("elements are zero-sized");
        }

        let self_start = self.as_ptr().addr();
        let elem_start = ptr::from_ref(element).addr();

        let byte_offset = elem_start.wrapping_sub(self_start);

        if !byte_offset.is_multiple_of(size_of::<T>()) {
            return None;
        }

        let offset = byte_offset / size_of::<T>();

        if offset < self.len() { Some(offset) } else { None }
    }
  1. Adapt it (by importing relevant modules, replacing &self with an explicitly passed argument slice: &[T].
    pub fn offset_in_slice<T>(list: &[T], element: &T) -> Option<usize> {
        let step = std::mem::size_of::<T>();
        if step == 0 {
            panic!("elements are zero-sized");
        }

        let self_start = list.as_ptr().addr();
        let elem_start = std::ptr::from_ref(element).addr();

        let byte_offset = elem_start.wrapping_sub(self_start);
        if byte_offset % step != 0 { return None; }

        let offset = byte_offset / step;
        if offset < list.len() { Some(offset) } else { None }
    }

Will not work for those changes which require compiler support (features), though.