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.
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);
}
You have to refer to the method using fully-qualified syntax. In a nutshell: <T>::{method_name}
where T
is the type and {method_name}
is the name of the method. For example, if you're modifying a [i32]
then you'd to prefix the method name with <[i32]>::
like this:
fn apply_fn<T, U>(t: T, t_fn: fn(T) -> U) -> U {
t_fn(t)
}
fn main() {
let mut items: Vec<i32> = vec![1, 2, 3];
let slice: &mut [i32] = items.as_mut_slice();
let first_split = apply_fn(slice, <[i32]>::split_first_mut);
let slice: &mut [i32] = items.as_mut_slice();
let last_split = apply_fn(slice, <[i32]>::split_last_mut);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.