简体   繁体   English

在外部函数中访问Go结构的值

[英]Access values of Go struct in external function

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). 我想返回*release.Name的值,而不是仅仅打印出来,以便我可以从另一个函数访问该值,但是我不了解在这种情况下返回的工作方式(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? 有人可以指出我正确的方向吗?

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 := ). 在指示的行上,定义一个名为release变量,等于releases[0] ,该变量仅作用于else子句(使用:= )。 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 . 看起来您还需要将release类型更改为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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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