[英]how can i choose array size in stract type (golang)
我需要做这样的事情:在 go 语言中,请帮助,谢谢
var size_IO= map[string]int{"AI":32,"DI":64,"AO":32}
type IO_point struct{
Name string
}
type AI struct {
CART [64]IO_point
Type string
IO_points [size_IO[Type]]IO_point
}
简短的回答:你不能这样做。
数组的长度是类型声明的一部分,它的值必须在编译时解决。 所以它应该是恒定的。
const arr_size= 5
type IO_point struct {
Name string
}
type AI struct {
CART [64]IO_point
Type string
IO_points [arr_size]IO_point
}
在您的情况下,您需要一个动态数据结构且比数组更灵活的切片。 这是一个例子:
var size_IO = map[string]int{"AI": 32, "DI": 64, "AO": 32}
type IO_point struct {
Name string
}
type AI struct {
CART [64]IO_point
Type string
IO_points []IO_point
}
func NewAi(cart [64]IO_point, t string) AI {
return AI{
CART: cart,
Type: t,
IO_points: make([]IO_point, 0, size_IO[t]),
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.