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

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

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

问题

我需要做类似这样的事情:
在Go语言中,请帮忙,谢谢。

  1. var size_IO = map[string]int{"AI": 32, "DI": 64, "AO": 32}
  2. type IO_point struct {
  3. Name string
  4. }
  5. type AI struct {
  6. CART [64]IO_point
  7. Type string
  8. IO_points [size_IO[Type]]IO_point
  9. }

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

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

英文:

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

  1. var size_IO= map[string]int{"AI":32,"DI":64,"AO":32}
  2. type IO_point struct{
  3. Name string
  4. }
  5. type AI struct {
  6. CART [64]IO_point
  7. Type string
  8. IO_points [size_IO[Type]]IO_point
  9. }

答案1

得分: 3

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

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

  1. const arr_size = 5
  2. type IO_point struct {
  3. Name string
  4. }
  5. type AI struct {
  6. CART [64]IO_point
  7. Type string
  8. IO_points [arr_size]IO_point
  9. }

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

  1. var size_IO = map[string]int{"AI": 32, "DI": 64, "AO": 32}
  2. type IO_point struct {
  3. Name string
  4. }
  5. type AI struct {
  6. CART [64]IO_point
  7. Type string
  8. IO_points []IO_point
  9. }
  10. func NewAi(cart [64]IO_point, t string) AI {
  11. return AI{
  12. CART: cart,
  13. Type: t,
  14. IO_points: make([]IO_point, 0, size_IO[t]),
  15. }
  16. }
英文:

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.

  1. const arr_size= 5
  2. type IO_point struct {
  3. Name string
  4. }
  5. type AI struct {
  6. CART [64]IO_point
  7. Type string
  8. IO_points [arr_size]IO_point
  9. }

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

  1. var size_IO = map[string]int{"AI": 32, "DI": 64, "AO": 32}
  2. type IO_point struct {
  3. Name string
  4. }
  5. type AI struct {
  6. CART [64]IO_point
  7. Type string
  8. IO_points []IO_point
  9. }
  10. func NewAi(cart [64]IO_point, t string) AI {
  11. return AI{
  12. CART: cart,
  13. Type: t,
  14. IO_points: make([]IO_point, 0, size_IO[t]),
  15. }
  16. }

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:

确定