Static reference to empty slice or vec

I can get something of type &'static str using string literals.

I need a static immutable reference to an empty slice or vec. Is there any function that returns something of type &'static Vec<T> or &'static [T] with no content?

const FOO: &[usize] = &[];

fn main() {
    println!("FOO = {:?}", FOO);
}

(Playground)

This seems to work for me…

&[] seems to work indeed. I missed that syntax :blush:
Can I get some immutable ref to Vec<T>. A custom constant is possible, but is there any in the stdlib?

As I understand it, a static reference to Vec<T> is only possible using the lazy_static crate, since it needs space on the Heap, which is only allocatable during runtime.

Aside of that, whenever I do write &Vec<T> as a type anywhere, clippy barfs at me, that this is rarely necessary.

But I am a beginner in this regard myself.

Vec in std::vec - Rust is const but not yet available on stable.

The original fn can be written as:

fn empty<T>() -> &'static [T] {
   &[]
}

That way compiler can infer the type for you rather than hardcoding a specific type.

You probably want a static reference to a slice, not Vec. The main difference is that Vec can grow, but static reference requires it to be immutable, so you pay for a type that can grow but can't.

2 Likes

You can also just use <&[T]>::default().

You don't have to use lazy_static. You can create an object at runtime and get a &'static T using Box::leak.

1 Like