dongzhang5006 2019-01-03 20:24
浏览 102

如何知道Golang中是否填充了空的struct var? [重复]

In Python I can do something like this:

aModel = None
models = somefunction()
for model in models:
    if model.cool is False and model.somenumber > -5:
        aModel = model
        break

if aModel:
    print("We found a model we like!!")

I'm trying to do the same thing in Golang. After initialization, a variable of some struct already IS a struct and already HAS values though (such as false for a bool var, and 0 for an int var).

So considering the following code:

type SomeModel struct {
    cool bool
    somenumber int
}

func main() {

    somemodels = somefunction()

    var aModel SomeModel
    for _, v := range somemodels {
        fmt.Println(v)
        if (v.cool == false && v.somenumber > -5) {
            aModel = v
        }
    }
    fmt.Println(aModel)
}

If this prints out {false 0}, how can I know whether this is a model I found in the slice, or if it's the default model I set before the loop?

I can of course set another variable like foundamodel := false and set that to true if I found something, but that doesn't really seem like the obvious way to go.

Or is it in Go?

</div>
  • 写回答

1条回答 默认 最新

  • dongxiatuo9827 2019-01-03 20:31
    关注

    You can use a pointer instead of a concrete value:

    var aModel *SomeModel
    for _, v := range somemodels {
        fmt.Println(v)
        if v.cool == false && v.somenumber > -5 {
            aModel = &v
            break
        }
    }
    if aModel != nil {
        fmt.Println(*aModel)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据