英文:
How to clear struct values except certain fields with struct's method
问题
我有一个结构体。我想要清除除了一些公共字段(例如Name
、Gender
)之外的所有字段,通过方法来实现该功能应该如何操作?
在我的实际代码中,结构体中有很多字段,所以手动重置那些敏感字段不是我的选择。
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("Hidding secret...")
a.Secret1 = ""
a.Secret2 = ""
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论