Search code examples
methodsrustprimitive-types

Access the methods of primitive Rust types


How can I access the methods of primitive types in Rust?

Concretely, I want to pass either one of the two slice methods split_first_mut and split_last_mut to a function operating on slices. I know you can wrap them in closures as a workaround, but I’d like to know if direct access is possible.


Solution

  • You can access the methods on primitives just like regular types:

    u8::to_le();
    str::from_utf8();
    <[_]>::split_first_mut();
    

    You can create a function that accepts a slice ops function:

    fn do_thing<T>(f: impl Fn(&mut [u8])) -> Option<(&mut T, &mut [T])>) {
        // ...
    }
    

    And pass in both split_first_mut and split_last_mut:

    fn main() {
        do_thing(<[_]>::split_first_mut);
        do_thing(<[_]>::split_last_mut);
    }