📜  Golang 中的reflect.Zero()函数示例

📅  最后修改于: 2021-10-25 02:54:16             🧑  作者: Mango

Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Zero()函数用于获取代表指定类型的零值的Value。要访问此函数,需要在程序中导入反射包。

下面的例子说明了上述方法在 Golang 中的使用:

示例 1:

func Zero(typ Type) Value

输出:

// Golang program to illustrate
// reflect.Zero() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
func main() {
    s := struct{ A int }{0}
    field := reflect.ValueOf(s).Field(0)
  
    fmt.Println(field.Interface())
      
    // use of Zero() method
    fmt.Println(reflect.Zero(field.Type()))
  
    fmt.Println(reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type())))
}
         

示例 2:

0
0
false

输出:

// Golang program to illustrate
// reflect.Zero() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
func main() {
    s := struct{ A int }{0}
    field := reflect.ValueOf(s).Field(0)
  
    fmt.Println(field.Interface())
      
    // use of Zero() method
    fmt.Println(reflect.Zero(field.Type()))
    fmt.Println(reflect.TypeOf(field.Interface()))
  
    // use of Zero() method
    fmt.Println(reflect.TypeOf(reflect.Zero(field.Type())))
      
    // use of Zero() method
    fmt.Println(reflect.DeepEqual(field.Interface(),
                       reflect.Zero(field.Type())))
  
    fmt.Println(reflect.DeepEqual(field.Interface(), 
            int(reflect.Zero(field.Type()).Int())))
    fmt.Println(reflect.DeepEqual(s, struct{ A int }{} ))
    fmt.Println(reflect.DeepEqual(s, struct{ A int }{0} ))
}