Home > Software engineering >  How to send a struct field to a function and modify it inside the function
How to send a struct field to a function and modify it inside the function

Time:10-13

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

CodePudding user response:

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

func MyFunc(mString *string){
    *mString = "SOMETHING"
}
  •  Tags:  
  • go
  • Related