Reputation: 3344
I have the following function declararion, which works and prints out correctly.
import (
"fmt"
"github.com/google/go-github/github"
)
func LatestTag(user, project string) {
client := github.NewClient(nil)
releases, _, err := client.Repositories.ListTags(user, project, nil)
if err != nil {
fmt.Printf("error: %v\n", err)
} else {
release := releases[0]
fmt.Printf("Version: %+v\n", *release.Name)
}
}
EDIT
I have modified the function to return a string (I don't think this is right) but hopefully it can help shed some light on what I am trying to do.
import (
"fmt"
"github.com/google/go-github/github"
)
func LatestTag(user, project string) string {
client := github.NewClient(nil)
releases, _, err := client.Repositories.ListTags(user, project, nil)
var release string
if err != nil {
fmt.Printf("error: %v\n", err)
} else {
release := releases[0]
}
return *release.Name
}
I would like to return the value of *release.Name
rather than just print it out so that I can access the value from another function but I don't understand how returning works in this case (very new to Go).
I was thinking I could just return the struct as a string but get errors when I run it.
release.Name undefined (type string has no field or method Name)
Which makes me think that I'm not approaching this correctly. Can somebody point me in the right direction?
Upvotes: 0
Views: 180
Reputation: 25129
One problem is here:
var release string
...
if err != nil {
...
} else {
release := releases[0] // <-- here
}
At the line indicated you define a new variable called release
equal to releases[0]
which is scoped only to the else
clause (use of :=
). That then goes out of scope immediately. I'm surprised you don't get an unused variable warning. Looks like you also need to change the type of release
to github.RepositoryTag
. Try:
var release github.RepositoryTag
...
if err != nil {
...
} else {
release = releases[0] // note equals sign
}
However a more idiomatic way to do this would be something like (untested):
func LatestTag(user, project string) (string, error) {
client := github.NewClient(nil)
if releases, _, err := client.Repositories.ListTags(user, project, nil); err != nil {
return "", err
} else {
release := releases[0]
return *release.Name, nil
}
}
Upvotes: 1