英文:
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"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论