-1

Does Go allow functions to add array length constraints to the signature, or would length still require a runtime check?

mcandre
  • 22,868
  • 20
  • 88
  • 147
  • 5
    Arrays DO have fixes lengths. Slices, on the other hand, do not, and you cannot enforce slice length via a function signature. –  Nov 26 '16 at 18:53
  • Actually there's a way. Possible duplicate of [Is it possible to trigger compile time error with custom library in golang?](http://stackoverflow.com/questions/37270743/is-it-possible-to-trigger-compile-time-error-with-custom-library-in-golang/37271129#37271129) – icza Nov 26 '16 at 21:03

1 Answers1

2

For arrays it is more than possible, it is required. For slices it is impossible.

package main

import (
    "fmt"
)

func main() {
    d := [2]int{1, 2}
    fmt.Println(sum(d))
}

func sum(data [2]int) int {
    return data[0] + data[1]
}

https://play.golang.org/p/-VMxyDvwUt

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105