dptsivmg82908 2013-02-11 04:24
浏览 55
已采纳

在Go中,如何在结构中带有指向数组的指针?

I would have expected this code to work:

package main

type Item struct {
  Key string
  Value string
}

type Blah struct {
  Values []Item
}

func main() {
  var list = [...]Item {
    Item {
      Key : "Hello1",
      Value : "World1",
    },
    Item {
      Key : "Hello1",
      Value : "World1",
    },
  }

  _ = Blah {
    Values : &list,
  }
}

I thought this would be the correct way of doing this; Values is a slice, list is an array. &list should be a slice, which is assignable to Item[], right?

...but instead, it errors with the message:

cannot use &list (type *[2]Item) as type []Item in assignment

In C, you'd write:

struct Item {
  char *key;
  char *value;
};

struct Blah {
   struct Item *values;
};

How do you do that in Go?

I saw this question: Using a pointer to array

...but either the answers are for a previous version of Go, or they're just plain wrong. :/

  • 写回答

3条回答 默认 最新

  • doutan5844 2013-02-11 04:38
    关注

    A slice is not simply a pointer to an array, it has an internal representation which contains its length and capacity.

    If you want to get a slice from list you can do:

    _ = Blah {
        Values : list[:],
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line