英文:
Golang Array Type Confusion
问题
我正在尝试为Google Drive的GoLang API提供参数(尽管你可能不需要了解API的任何内容来回答这个问题)。我对Go语言还不熟悉,我的构建错误消息让我感到困惑。
其中一个可选参数是一个父文件夹的数组,用于存储上传的文件。父文件夹使用ParentReference结构体引用。请参考以下Golang代码片段:
parent := drive.ParentReference{Id: parent_folder}
parents := [...]*drive.ParentReference{&parent}
driveFile, err := service.Files.Insert(
&drive.File{Title: "Test", Parents: parents}).Media(goFile).Do()
我得到的构建错误是在上述代码片段的最后一行:
cannot use parents (type [1]*drive.ParentReference) as type []*drive.ParentReference in field value
我对[1]*Type和[]*Type之间的区别感到困惑。似乎前者是具有特定长度的数组,而后者是没有指定长度的数组。在这里,任何澄清都将是有用的。
英文:
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.
答案1
得分: 4
正如你所指出的,切片(slices)和数组(arrays)在Go语言中是两种不同的类型,它们的行为也不同。因此,[]Type和[1]Type是两种不同的东西,不能互换使用。你可以查看这篇关于切片的优秀解释来获取更多关于它们的信息。
不过,你的修复方法比必要的要复杂一些。你应该可以直接使用以下代码:
parents := []*drive.ParentReference{&parent}
而不是你目前使用的代码:
parents := [...]*drive.ParentReference{&parent}
如果你将变量实例化为切片,就不需要后续再对其进行切片操作了。
英文:
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.
答案2
得分: 0
我的问题显然是不知道要搜索什么- []*Type 不是一个很好的谷歌查询。
不过我找到了答案,[1]*Type 是一个数组,而[]*Type 是一个切片。所以解决办法就是简单地对 parents 进行切片,像这样:
Parents: parents[:]
就可以解决问题了。
英文:
My problem apparently was not knowing what to search for - []*Type isn't a very good Google query.
I found the answer though, [1]*Type is an array while []*Type is a slice. So the solution is to simply slice parents, so something like:
Parents: parents[:]
Does the trick.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论