You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何将切片转为数组引用?解决类型不匹配编译错误

Fixing Mismatched Types: Converting a Slice to a Fixed-Size Array Reference for FFI

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:

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_into returns a Result<&[u8;16], _>—since you know your chunk is always 16 bytes, expect (or unwrap) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:22:34