Rust中如何将切片转为数组引用?解决类型不匹配编译错误
The error you're seeing happens because Rust distinguishes between dynamic slices (&[u8]) and fixed-size array references (&[u8; 16]). The FFI function expects a reference to an exact 16-byte array, but your slice is dynamically sized (even though you know its length is 16 at runtime). Here are two reliable ways to fix this:
1. Safe Approach: Use try_into (Recommended)
Rust's standard library provides a safe try_into method for slices that attempts to convert them into a fixed-size array reference. This method does a runtime length check to ensure safety:
fn a_ffi_function(buffer: &[u8; 16]) { unsafe { } } fn main() { let buffer = [0u8; 64]; for i in 0..4 { let chunk = &buffer[i*16..(i+1)*16]; // Convert the slice to a &[u8;16] safely let array_ref: &[u8; 16] = chunk.try_into().expect("Chunk must be exactly 16 bytes"); a_ffi_function(array_ref); } }
- Why this works:
try_intoreturns aResult<&[u8;16], _>—since you know your chunk is always 16 bytes,expect(orunwrap) will safely unwrap the valid reference. If you ever accidentally change the slice range later, this will panic with a clear message instead of causing undefined behavior.
2. Unsafe Approach: Direct Pointer Casting
If you want to skip the runtime check (though it's rarely necessary here), you can use unsafe code to cast the slice's pointer to an array pointer. Only do this if you're 100% certain the slice length is exactly 16 bytes:
fn a_ffi_function(buffer: &[u8; 16]) { unsafe { } } fn main() { let buffer = [0u8; 64]; for i in 0..4 { let chunk = &buffer[i*16..(i+1)*16]; // Assert the length first to catch mistakes early assert_eq!(chunk.len(), 16, "Chunk must be exactly 16 bytes"); // Cast the slice pointer to an array reference let array_ref: &[u8; 16] = unsafe { &*(chunk.as_ptr() as *const [u8; 16]) }; a_ffi_function(array_ref); } }
- The
assert_eq!is crucial here—it acts as a safeguard to ensure you don't accidentally pass a slice of the wrong length, which would lead to undefined behavior. Without it, an incorrect slice could cause memory safety issues.
Key Context
The compiler can't automatically convert &[u8] to &[u8;16] because slices are dynamically sized types (DST). The compiler can't verify at compile time that your slice will always be exactly 16 bytes long, even though your loop logic makes that obvious to you.
内容的提问来源于stack exchange,提问作者buckle2000

