Slice type issue

I am using Rust v1.78.

use std::env;

let value: &[&str] = env::var("key").map_or_else(|_e| &["default"], |v| if v == "something" { &[] } else { &["val"] } );

I got this error in &[] part

mismatched types
expected reference `&[&str; 1]`
   found reference `&[_; 0]`

let empty_slice: &[&str] = &[]; works, so why doesn't this work? How can I fix this?

Thanks!

Because by default &["default"] is of type &[&str; 1] as rustc points out (a reference to an array of size 0).
That it not the same type as &[&str] (a slice of &str) nor the same as &[&str; 0] (a reference to a 0-length array).
You can howerver coerce a reference to an array to a slice using &["default"][..].

let value: &[&str] = env::var("key").map_or_else(|_e| &["default"][..], |v| if v == "something" { &[] } else { &["val"] } );
1 Like

@jer Great! This works perfect. didnt know &["default"] was the issue. thanks for the tip!