Go函数能够指定特定的数组长度吗?

huangapple go评论69阅读模式
英文:

Can Go functions specify a particular array length?

问题

Go允许函数在签名中添加数组长度约束吗,还是长度仍然需要在运行时进行检查?

英文:

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

答案1

得分: 2

对于数组来说,这不仅是可能的,而且是必需的。对于切片来说,这是不可能的。

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

英文:

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

huangapple
  • 本文由 发表于 2016年11月27日 02:52:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/40821895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定