P Varga
P Varga

Reputation: 20219

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

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?

Upvotes: 0

Views: 75

Answers (1)

icza
icza

Reputation: 417412

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

Upvotes: 4

Related Questions