GoLang返回的Package变量值未更新

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

GoLang value not updated for returned Package variable

问题

你好,以下是代码的翻译:

package main

import "fmt"

type Person struct{
    FirstName, LastName string
    Age int
}

var p Person = Person{"Bob","Rolf",15}

func GetPerson() Person{
    return p
}

func main(){
    fmt.Println(GetPerson())
    rP := GetPerson()
    rP.Age = 40
    fmt.Println(GetPerson())
}

这段代码定义了一个名为Person的结构体,包含了FirstName、LastName和Age三个字段。然后创建了一个名为p的Person实例,并将其Age设置为15。

GetPerson()函数返回了全局变量p的值。

在main函数中,首先打印了GetPerson()函数的返回值,即p的值。

然后,通过将GetPerson()函数的返回值赋给rP变量,创建了一个新的Person实例,并将其Age设置为40。

最后,再次打印GetPerson()函数的返回值,发现Age仍然是15,没有被更新为40。

这是因为在Go语言中,结构体是值类型,当将结构体赋值给一个新的变量时,会创建一个新的副本,而不是引用原始结构体。因此,对rP的修改不会影响到原始的p变量。

如果想要修改原始的p变量,可以将GetPerson()函数返回一个指向Person结构体的指针,然后通过指针修改Age字段的值。例如:

func GetPerson() *Person{
    return &p
}

这样,对rP的修改就会影响到原始的p变量。

英文:

Hi I am new to go and am trying to get my head around why the Package value that is returned by the method GetPerson() is not updated when I updated the returned value. I know how i could change the method to make it work, Im more after an explanation of what is going on?

package main 

import "fmt"

type Person struct{
	FirstName, LastName string
	Age int
}

var p Person = Person{"Bob","Rolf",15}

func GetPerson() Person{
	return p
}

func main(){
	fmt.Println(GetPerson())
	rP := GetPerson()
	rP.Age = 40
	fmt.Println(GetPerson())
}    

答案1

得分: 4

GetPerson函数返回值的副本。对副本的更改不会反映在原始值上。

返回一个指向该值的指针,并通过指针进行更新。

package main

import "fmt"

type Person struct{
  FirstName, LastName string
  Age int
}

var p Person = Person{"Bob","Rolf",15}

func GetPerson() *Person{  // 注意 *
  return &p                // 注意 &
}

func main(){
  fmt.Println(GetPerson())
  rP := GetPerson()
  rP.Age = 40
  fmt.Println(GetPerson())
}

playground示例

英文:

GetPreson returns a copy of the value. Changes to the copy are not reflected in the original.

Return a pointer to the value and update through the pointer.

package main 

import "fmt"

type Person struct{
  FirstName, LastName string
  Age int
}

var p Person = Person{"Bob","Rolf",15}

func GetPerson() *Person{  // note *
  return &p                // note &
}

func main(){
  fmt.Println(GetPerson())
  rP := GetPerson()
  rP.Age = 40
  fmt.Println(GetPerson())
}    

playground example

huangapple
  • 本文由 发表于 2016年8月22日 03:30:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/39068105.html
匿名

发表评论

匿名网友

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

确定