Using function argument (parameter) in a constant context in Go

66 views Asked by At

Is it somehow possible to use a function's argument in a constant context?
For example

func example(size int) {
  one := [size]int{}  // Error: non-constant array bound 'size' 
  const two = size    // Error: const initializer 'size' is not a constant
}

Is size not effectively constant in these cases? If not, why?

1

There are 1 answers

0
icza On BEST ANSWER

No, this is not possible in Go. Go constants are compile-time constructs, while parameter values only exist at runtime.

Spec: Constant expressions:

Constant expressions may contain only constant operands and are evaluated at compile time.

Recommended reading: The Go Blog: Constants