Search code examples
gotype-safety

Can Go functions specify a particular array length?


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


Solution

  • 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