Zero out anonymous global struct

Viewed 234

I have following code

package main

import (
    "fmt"
)

var dog struct {
    Name  string
    Age   int
    Breed string
}

func main() {
    dog.Name = "Pongo"
    dog.Age = 7
    dog.Breed = "Dalmatian"
    fmt.Println(dog)

    // Reset struct.
    dog{} --- Problem point with error
    fmt.Println(dog)

    dog.Name = "Fluffy"
    dog.Breed = "Poodle"
    fmt.Println(dog)
}

I am trying to clear out the global struct in Reset. I know I can do it individually. I am looking into golang way of doing like we can do it for struct as follow

type Dog struct {
    Name  string
    Age   int
    Breed string
}

dog = Dog {}
2 Answers

If you have a variable of struct type, you may zero it by assigning the zero value of its type.

As noted by others, since you have a variable of anonymous type, the composite literal has to repeat the struct definition:

// Reset with struct literal:
dog = struct {
    Name  string
    Age   int
    Breed string
}{}

This is inconvenient. So just use a named type.

You could also do it with reflection:

// Reset using reflection:
p := &dog
v := reflect.ValueOf(p).Elem()
v.Set(reflect.New(v.Type()).Elem())

The advantage here is that we didn't have to repeat the struct definition, and this solution works with all structs (and other types too). But using reflection is slower. Again, just use a named type.

You may try the examples on the Go Playground.

What's wrong with the solution you proposed? That is how you would do it:

package main

import (
    "fmt"
)

type Dog struct {
    Name  string
    Age   int
    Breed string
}

var dog = Dog{}

func main() {
    dog.Name = "Pongo"
    dog.Age = 7
    dog.Breed = "Dalmatian"
    fmt.Println(dog)

    // Reset struct.
    dog = Dog{}
    fmt.Println(dog)

    dog.Name = "Fluffy"
    dog.Breed = "Poodle"
    fmt.Println(dog)
}
Related