Home > Software design >  How to clear struct values except certain fields with struct's method
How to clear struct values except certain fields with struct's method

Time:09-29

I have a struct. I want to clear all fields except some public fields, e.g. Name, Gender, how to implement the function through method?

In my real code, I have many fields in the struct, so reset those sensitive fields manually is not my option.

type Agent struct {
    Name    string
    Gender  string
    Secret1 string
    Secret2 string
}

func (a *Agent) HideSecret() {
    fmt.Println("Hidding secret...")
    new := &Agent{
        Name:   a.Name,
        Gender: a.Gender,
    }
    a = new
}

I tried a few combination of * and &, but it seems not working... Please help.

    James := Agent{
        Name:    "James Bond",
        Gender:  "M",
        Secret1: "1234",
        Secret2: "abcd",
    }

    fmt.Printf("[Before] Secret: %s, %s\n", James.Secret1, James.Secret2)
    James.HideSecret()
    fmt.Printf("[After]  Secret: %s, %s\n", James.Secret1, James.Secret2) // not working

The golang playground is here: https://go.dev/play/p/ukJf2Fa0fPI

CodePudding user response:

The receiver is a pointer. You have to update the object that the pointer points to:

func (a *Agent) HideSecret() {
    fmt.Println("Hidding secret...")
    cleaned := Agent{
        Name:   a.Name,
        Gender: a.Gender,
    }
    *a=cleaned
}
  •  Tags:  
  • go
  • Related