Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created November 19, 2018 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/27d27a1ac7fa99503e0737c28db53056 to your computer and use it in GitHub Desktop.
Save tanaikech/27d27a1ac7fa99503e0737c28db53056 to your computer and use it in GitHub Desktop.
Using String Values to []googleapi.Field for Golang

Using String Values to []googleapi.Field for Golang

This sample script is for using the string values to []googleapi.Field for Golang. The property of fields can often be used to the Google APIs. When such APIs are used by the Go library, there are the cases that fields parameter is required to be used. For example, at the quickstart of Drive API for golang, the value is directly put to Fields() like r, err := srv.Files.List().PageSize(10).Fields("nextPageToken, files(id, name)").Do(). For this situation, when the string value is put to Fields() as follows,

fields := "nextPageToken, files(id, name)"
r, err := srv.Files.List().PageSize(10).Fields(fields).Do()

the following error occurs.

cannot use fields (type string) as type googleapi.Field in argument to srv.Files.List().PageSize(10).Fields

So when []googleapi.Field is used for the value like below script, no error occurs.

fields := []googleapi.Field{"nextPageToken, files(id, name)"}
r, err := srv.Files.List().PageSize(10).Fields(fields...).Do()

But when "nextPageToken, files(id, name)" is given as a string variable like this,

v := "nextPageToken, files(id, name)"
fields := []googleapi.Field{v}
r, err := srv.Files.List().PageSize(10).Fields(fields...).Do()

the following error occurs.

cannot use v (type string) as type googleapi.Field in array or slice literal

There are the situation that it is required to give the fields parameters from outside. In this case, it can modify above script as follows. In this modified script, no error occurs and the result can be retrieved.

v := "nextPageToken, files(id, name)"
conv := googleapi.Field(v)
fields := []googleapi.Field{conv}
r, err := srv.Files.List().PageSize(10).Fields(fields...).Do()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment