Error with non matching type: Option<&[u8]> and Option<&[u8;32]>

Viewed 146

I playing with the Rust code, and I've got to a place in which I have a problem with converting Option<&[u8; 32]> to Option<&[u8]>.

A (very) simplified example:

pub type Foo = [u8; 32];

fn fun_one(inp: Option<&[u8]>) {
    println!("{:?}", inp);
}

fn fun_two(x: Option<&Foo>) {
    fun_one(x)
}

fn main() {
    let x = [11u8; 32];
    fun_two(Some(&x));
}

Link: Rust Playground

error[E0308]: mismatched types
 --> src/main.rs:8:13
  |
8 |     fun_one(x)
  |             ^ expected slice `[u8]`, found array `[u8; 32]`
  |
  = note: expected enum `Option<&[u8]>`
             found enum `Option<&[u8; 32]>`
1 Answers

A slice isn't just a pointer over an array. It's both the pointer to the data and a length (see Arrays and Slices) as it refers to only a part of the array. This is why the types aren't compatible.

What you want here is a slice over the whole array, which you get with the .. full range expression: slice = &array[..].

Having an option, you can conditionnaly apply this transformation using map.

Combining all this:

fn fun_two(x: Option<&Foo>) {
    fun_one(x.map(|a| &a[..]))
}
Related