如何使用结构体的方法清除除特定字段之外的结构体值

huangapple go评论68阅读模式
英文:

How to clear struct values except certain fields with struct's method

问题

我有一个结构体。我想要清除除了一些公共字段(例如NameGender)之外的所有字段,通过方法来实现该功能应该如何操作?

在我的实际代码中,结构体中有很多字段,所以手动重置那些敏感字段不是我的选择。

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

func (a *Agent) HideSecret() {
	fmt.Println("隐藏秘密...")
	new := &Agent{
		Name:   a.Name,
		Gender: a.Gender,
	}
	a = new
}

我尝试了一些*&的组合,但似乎没有起作用...
请帮忙看看。

James := Agent{
	Name:    "詹姆斯·邦德",
	Gender:  "男",
	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) // 不起作用

Golang Playground 在这里:https://go.dev/play/p/ukJf2Fa0fPI

英文:

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

答案1

得分: 2

接收器是一个指针。你必须更新指针所指向的对象:

func (a *Agent) HideSecret() {
    fmt.Println("隐藏秘密...")
    cleaned := Agent{
        Name:   a.Name,
        Gender: a.Gender,
    }
    *a = cleaned
}
英文:

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
}

</details>



# 答案2
**得分**: 0

如果你只想清除字段,这是一个简单的解决方案,它可以节省一些内存。

```go
func (a *Agent) HideSecret() {
   fmt.Println("隐藏秘密...")
   a.Secret1 = ""
   a.Secret2 = ""
}
英文:

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

func (a *Agent) HideSecret() {
   fmt.Println(&quot;Hidding secret...&quot;)
   a.Secret1 = &quot;&quot;
   a.Secret2 = &quot;&quot;
}

huangapple
  • 本文由 发表于 2022年9月29日 02:52:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/73886522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定