dspv70887 2015-11-22 08:12
浏览 717
已采纳

类型不匹配的* string和string

I am attempting to run a conditional to basically see if the object is empty but I keep getting (similar variations) of this error:

invalid operation: release.Name == "" (mismatched types *string and string)

Here is the code that is dying:

import (
    "github.com/google/go-github/github"
)

func TestLatestTag(user, project string) {

    var client *github.Client
    client = github.NewClient(nil)

    releases, _, err := client.Repositories.ListTags(user, project, nil)
    var release github.RepositoryTag

    if err != nil {
        fmt.Println("Error")
    } else {
        if release.Name == "" {
            fmt.Println("None")
        } else {
            fmt.Println(releases[0])
        }
    }
}

If I change the if statement to *release.Name == "" as the error suggests I get a different error, which I don't really understand:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x26fd]

goroutine 1 [running]:

I'm sure there is any easy way to do this but I am not very familiar with handling objects/structs

  • 写回答

3条回答 默认 最新

  • drbi19093 2015-11-22 09:22
    关注

    As per your code you have declared var release github.RepositoryTag, but you have not initialized it.

    In structure RepositoryTag, Name is declared as *string which is a pointer and in case of release.Name == "", string comparison is attempted which is incorrect hence "mismatched types *string and string" error.

    In case of *release.Name == "", since release is not yet initialized, it is complaining "invalid memory address or nil pointer dereference"

    You need to do two things, 1st initialize, release and second, check release.Name = nil.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器