简体   繁体   中英

Golang Array Type Confusion

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM