清空已经赋值的struct
type A struct {
Name string
Level int
}
type B struct {
Skill string
}
func main() {
a := A{"Momo",1}
b := B{"Starfall"}
// outputs
// {"Momo",1}
// {"Starfall"}
clear(a)
clear(b)
// outputs
// {,0}
// { }
}
func clear(v interface{}) {
p := reflect.ValueOf(v).Elem()
p.Set(reflect.Zero(p.Type()))
}
判断是否为空的strct
type Session struct {
playerId string
beehive string
timestamp time.Time
}
session = Session{};
if (Session{}) == session {
fmt.Println("is zero value")
}
//或者判断其中一个值
if session.playerId == "" {
fmt.Println("is zero value")
}
清空array和map
//清空array
var slice []string
slice = []string{"first"}
slice = slice[:0] //或者 slice = nil
//清空map
var m map[string]string
m = make(map[string]string)
m["name"] = "yourname"
m = nil
//或者这样
/*
for k := range m {
delete(m,k)
}
*/