[英]Access the methods of primitive Rust types
How can I access the methods of primitive types in Rust?如何访问 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.具体来说,我想将两个切片方法split_first_mut
和split_last_mut
中的任何一个传递给在切片上运行的 function。 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:您可以创建一个接受切片操作 function 的 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
:并传入split_first_mut
和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.简而言之: <T>::{method_name}
其中T
是类型, {method_name}
是方法的名称。 For example, if you're modifying a [i32]
then you'd to prefix the method name with <[i32]>::
like this:例如,如果您正在修改[i32]
,那么您需要在方法名称前加上<[i32]>::
前缀,如下所示:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.