Using String Values to []googleapi.Field for Golang

Gists

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()

 Share!