验证结构变量是否为空或非空

huangapple go评论85阅读模式
英文:

Validate if struct variable is empty or not

问题

首先,让我们来看一下以下的代码片段:

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 != "" {
	fmt.Println(para1)
}

你可以使用空字符串 "" 来验证结构体变量是否为nil。在Go语言中,结构体类型的零值是一个具有所有字段都是零值的结构体。对于字符串类型的字段,零值是空字符串 ""。因此,你可以通过检查结构体的字符串字段是否为空字符串来验证结构体变量是否为nil。在上面的代码中,我们使用 para1.email != "" 来验证 para1 是否为nil。如果 para1.email 不是空字符串,就打印出 para1

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

First of all, look at the following code snippet:

package main

import (
	"fmt"
)

func main() {

	var para1 struct {
		email, addr string
	}

	para1.email = "test@test.com"

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

}

When I compile this code, I've got the compiler error:

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

How can I validate if my struct variable, if nil or not? Or I have to validate of property like

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

答案1

得分: 8

你可以将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

Go编程语言规范

零值

当分配内存来存储一个值时,无论是通过声明还是通过调用make或new,如果没有提供显式的初始化,该内存将被赋予默认初始化。这个值的每个元素都被设置为其类型的零值:布尔类型为false,整数类型为0,浮点数类型为0.0,字符串类型为"",指针、函数、接口、切片、通道和映射类型为nil。这个初始化是递归进行的,因此,如果没有指定值,结构体数组的每个元素的字段都将被置为零值。

英文:

You can compare the struct to its zero value. You can test the string for its zero (empty) value "" or test for string length zero. For example,

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)
	}
}

Output:

{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.

答案2

得分: 5

我知道这段时间很安静,但一种很好的可重用的方法来验证结构体是否为空是使用内置的"reflect"包。它允许你将结构体与一个空的副本进行比较。以下是使用基于反射的isEmpty函数的代码版本。

package main

import (
	"fmt"
	"reflect"
)

func isEmpty(object interface{}) bool {
	// 首先检查常规的空定义
	if object == nil {
		return true
	} else if object == "" {
		return true
	} else if object == false {
		return true
	}

	// 然后检查是否为结构体
	if reflect.ValueOf(object).Kind() == reflect.Struct {
		// 创建一个空的结构体副本进行比较
		empty := reflect.New(reflect.TypeOf(object)).Elem().Interface()
		if reflect.DeepEqual(object, empty) {
			return true
		}
	}
	return false
}

func main() {

	var para1 struct {
		email, addr string
	}

	para1.email = "test@test.com"

	if isEmpty(para1) {
		fmt.Println("它是空的")
	} else {
		fmt.Println(para1)
	}
}

你可以在这里查看代码:链接

英文:

I know this has been quiet for a while, but a nice reusable way to validate that a struct is empty is to use the "reflect" built-in. It allows you to compare against an empty copy of your struct. Here is a version of your code using an isEmpty function based on reflect.

package main

import (
    "fmt"
    "reflect"
)

func isEmpty(object interface{}) bool {
    //First check normal definitions of empty
    if object == nil {
	    return true
    } else if object == "" {
	    return true
    } else if object == false {
	    return true
    }

    //Then see if it's a struct
    if reflect.ValueOf(object).Kind() == reflect.Struct {
	    // and create an empty copy of the struct object to compare against
	    empty := reflect.New(reflect.TypeOf(object)).Elem().Interface()
	    if reflect.DeepEqual(object, empty) {
		    return true
	    }
    }
    return false
}

func main() {

    var para1 struct {
	    email, addr string
    }

    para1.email = "test@test.com"

    if isEmpty(para1) {
	    fmt.Println("It's empty")
    } else {
	    fmt.Println(para1)
    }
}

http://play.golang.org/p/geqHKMSWzp

答案3

得分: 3

var para1 struct {
email, addr string
}

在这行之后,para1 是一个包含两个空字符串的结构体值 你可以在这里看到

只有切片、映射、通道、指针和函数可以是 nil。因此,将 para1nil 进行比较是没有意义的,编译器会报错。

诚然,错误信息可能可以更好。

如果你想知道 para1 是否为空,你应该给它的类型命名,并在其上声明一个方法:

type Parameter struct {
email, addr string
}

func (p Parameter) Empty() bool {
return (p.email != "" && p.addr != "")
}

英文:
var para1 struct {
    email, addr string
}

After this line, para1 is a struct value containing 2 empty strings as you can see here.

only slices, maps, channels, pointers and functions can be nil. Therefore comparing para1 to nil does not make sense and the compiler is complaining about that.

Admittedly the error message could be better.

If you want to know if para1 is empty you should give its type a name and declare a method on it:

type Parameter struct {
    email, addr string
}

func (p Parameter) Empty() bool {
    return (p.email != "" && p.addr != "")
}

huangapple
  • 本文由 发表于 2014年8月17日 20:01:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/25349004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定