Reputation: 15
Context: I needed to flatten a vector of arrays in Rust, and I found the following code from a Rust community member:
fn flatten<T: Clone, const N: usize>(data : Vec<[T; N]>) -> Vec<T> {
unsafe {
from_raw_parts(data.as_ptr() as *const _, data.len() * N).to_vec()
}
}
from_raw_parts
returns a slice from a raw pointer and a length. The raw pointer we're passing in has a type of *const [T;N]
, and I figure we would need to convert that to *const T
. However, this code converts it to *const _
and produces the same result as using *const T
.
So what is _
doing here? And is it good practice to use _
instead of an explicit type?
Upvotes: 1
Views: 982
Reputation: 71380
_
just means "infer the type from the context". In this case, the compiler infers it to be T
from the function's return type.
Regarding the second question, in general in Rust we tend to leave to the compiler what it can infer, but with unsafe code specifically because any mistake can be so dangerous I (and other people) prefer to specify each and every type explicitly.
Upvotes: 4