How to send a struct field to a function and modify it inside the function

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

How to send a struct field to a function and modify it inside the function

问题

在Go语言中,我试图将一个结构体字段传递给一个函数并对其进行修改,我正在寻找通用函数,并只修改传递给函数的字段,就像这样:

func MyFunc(mString *string){
    mString = "SOMETHING"
}

func main(){
   type mStruct struct{
      String1 string
      String2 string
   }
   myStruct := mStruct{String1:"SOME"}
   myFunc(&myStruct.String1)
   fmt.Println(myStruct)
}

我希望得到的结果是:String1: "SOMETHING",但实际上得到的是"SOME"。

有什么办法可以实现这个目标吗?
谢谢

英文:

In golang im trying to send a struct field to a function and modify it, im looking for generyc function and modify just the field passed to the function, like this:

func MyFunc(mString *string){
    mString = "SOMETHING"
}

func main(){
   type mStruct struct{
      String1 string
      String2 string
   }
   myStruct := mStruct{mStirng1:"SOME"}
   myFunc(&myStruct.String1)
   fmt.Println(myStruct)
}

I want to get the result as: String1: "SOMETHING" but im getting "SOME"

Any idea to achive this?
Thanks

答案1

得分: 1

你将指针设置为指向其他内容,而没有改变它的内容:

func MyFunc(mString *string){
    *mString = "SOMETHING"
}
英文:

You set the pointer to point to something else, you did not change the content of it:

func MyFunc(mString *string){
    *mString = "SOMETHING"
}

huangapple
  • 本文由 发表于 2022年10月12日 06:53:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/74034823.html
匿名

发表评论

匿名网友

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

确定