使用任何编程语言都会遇到判空的问题,那么Golang对于自定义的结构体类型如何判空呢?

其实空结构体可不是简单的与nil做比较哦。请看下面两种方法:

package main

import (
	"fmt"
	"reflect"
)

type A struct {
	name string
	age  int
}

func (a A) IsEmpty() bool {
	return reflect.DeepEqual(a, A{})
}

func main() {
	var a A

	if a == (A{}) { // 括号不能去
		fmt.Println("a == A{} empty")
	}

	if a.IsEmpty() {
		fmt.Println("reflect deep is empty")
	}
}

相关文章:

  • 2021-06-11
  • 2021-09-23
  • 2021-07-04
  • 2021-06-08
  • 2021-08-08
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2023-02-16
  • 2022-12-23
  • 2021-11-05
  • 2021-11-28
  • 2021-11-28
  • 2021-11-27
  • 2021-12-04
相关资源
相似解决方案