2

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("Hiding 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

2 Answers 2

2

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

func (a *Agent) HideSecret() {
    fmt.Println("Hiding secret...")
    cleaned := Agent{
        Name:   a.Name,
        Gender: a.Gender,
    }
    *a=cleaned
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to just clear the fields, this is an easy solution; it saves some memory

func (a *Agent) HideSecret() {
   fmt.Println("Hiding secret...")
   a.Secret1 = ""
   a.Secret2 = ""
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.