gpt4 book ai didi

go - 验证结构变量是否为空

转载 作者:IT王子 更新时间:2023-10-29 01:24:44 26 4
gpt4 key购买 nike

首先,看下面的代码片段:

package main

import (
"fmt"
)

func main() {

var para1 struct {
email, addr string
}

para1.email = "test@test.com"

if para1 != nil {
fmt.Println(para1)
}

}

当我编译这段代码时,出现编译错误:

./struct_func.go:15: cannot convert nil to type struct { email string; addr string }

我如何验证我的结构变量是否为 nil?或者我必须验证像

这样的属性
if para1.email != nil {
fmt.Println(para1)
}

最佳答案

您可以将 struct 与其零值进行比较。您可以测试 string 的零(空)值 "" 或测试 string 长度为零。例如,

package main

import (
"fmt"
)

func main() {
var para1 struct {
email, addr string
}
para1Zero := para1
para1.email = "test@test.com"
if para1 != para1Zero {
fmt.Println(para1)
}
if para1.email != "" {
fmt.Println(para1.email)
}
if len(para1.email) != 0 {
fmt.Println(para1.email)
}
}

输出:

{test@test.com }
test@test.com
test@test.com

The Go Programming Language Specification

The zero value

When memory is allocated to store a value, either through a declaration or a call of make or new, and no explicit initialization is provided, the memory is given a default initialization. Each element of such a value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

关于go - 验证结构变量是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com