duangan6797 2013-12-28 02:24
浏览 21
已采纳

Golang数组类型混淆

I'm trying to provide arguments to a Google Drive GoLang API (though you probably don't need to know anything about the API to answer the question). I'm new to Go and my build error message is confusing me.

One of the optional arguments is an array of parent folders into which an uploaded file should be stored in. A parent folder is referred to with a ParentRefernce struct. See the following snippet of Golang code:

parent := drive.ParentReference{Id: parent_folder}
parents := [...]*drive.ParentReference{&parent}
driveFile, err := service.Files.Insert(
  &drive.File{Title: "Test", Parents: parents}).Media(goFile).Do()

The build error I'm getting is for the last line of the above snippet: cannot use parents (type [1]*drive.ParentReference) as type []*drive.ParentReference in field value

My confusion is around the distinction between [1]*Type and []*Type. It seems like the former is a specific length array and the latter is an array without specified length. Any clarification here would be useful.

  • 写回答

2条回答 默认 最新

  • dsvtnz6350 2013-12-28 02:49
    关注

    As you noted, slices and arrays are two different types in Go, and behave differently. So []Type and [1]Type are two different things and cannot be used interchangeably. Check out the great explanation of slices for more information about them.

    Your fix is a bit more convoluted than it needs to be, however. You should be able to just use

    parents := []*drive.ParentReference{&parent}

    where you currently have

    parents := [...]*drive.ParentReference{&parent}

    If you instantiate the variable as a slice, you'll have no need to slice it later.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝