how can i choose array size in stract type (golang)

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

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
}

请注意,这是一个Go语言的代码片段,其中定义了一个AI结构体和相关的变量和类型。size_IO是一个映射,它将字符串类型的输入/输出类型与其对应的大小关联起来。IO_point是一个结构体,表示输入/输出点的名称。AI结构体包含一个名为CART的数组和一个名为Type的字符串,以及一个根据Type确定大小的IO_points数组。

希望对你有帮助!如果你有任何其他问题,请随时提问。

英文:

i need do something like this :
in go language,please help ,thanks

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
}

答案1

得分: 3

**简短回答:**你不能这样做。

数组的长度是类型声明的一部分,其值必须在编译时解析。因此,它应该是常量。

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
}

在你的情况下,你需要使用切片(slice),它是一种动态数据结构,比数组更灵活。这里是一个示例:

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]),
	}
}
英文:

Short answer: You cannot do this.

The length of the array is part of type declaration and its value must me resolved at compile time. So it should be constant.

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
}

In your situation you need a slice which is a dynamic data structure and more flexible than array. Here it is an example:

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]),
	}
}

huangapple
  • 本文由 发表于 2022年8月29日 03:17:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73521535.html
匿名

发表评论

匿名网友

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

确定