Creating a static slice in a const fn

Is it possible to create a static slice in a const fn?

I am trying to create a DSL for tensor operations with the goal of using const fns to do compile time shape inference. I would like to create a function that works like this

type Shape = &'static [usize];

const fn concat(a: Shape, b: Shape, dimension: usize) -> Shape {
    if a.len() != b.len() {
        panic!("ranks do not match");
    if dimension >= a.len() {
        panic!("dimension greater than rank");

    // doesn't work, isn't a.len() constant?
    let mut shape = [0; a.len()];

    let mut i = 0;
    while i < a.len() {
        if i == dimension {
            shape[i] = a[i] + b[i];
        } else if a[i] == b[i] {
            shape[i] = a[i];
        } else {
            panic!("unconcatenated dimensions don't match");
        i += 1;

    // doesn't work as shape is local and not static

Is there any way I can get this working while keeping Shape as a static slice?

I am aware that I could avoid this issue by redefining the Shape as one of the following

type Shape<const R: usize> = [usize; R];


const MAX_RANK: usize = 8;
struct Shape {
    rank: usize,
    shape: [usize; MAX_RANK],

While these solutions would work, they are less convenient either they require inferring the rank throughout the program or choosing a constant MAX_RANK.

const are functions that can be called at compile time, but not necessarily. They can still be called at runtime so your code needs to be valid for those cases too.


I hadn't considered this, I guess since it wouldn't be possible to create a static at runtime then this isn't possible. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.