What is the difference between the following two ways to initialize the user variable?

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

What is the difference between the following two ways to initialize the user variable?

问题

以下是要翻译的内容:

我是Golang的初学者。这个问题可能很简单,但是它真的让我困惑。

如果有一个User结构体:

type user struct{
    name string
    email string
}

以下两种方式初始化user变量有什么区别?

mike := user{"mike", "mike@email.com"}
lisa := &user{"lisa", "lisa@email.com"}
英文:

I am a starter in Golang. This question may be very easy but it really confused me.

if there is a User struct:

type user struct{
    name string
    email string
}

What is the difference between the following two ways to initialize the user variable?

mike := user{"mike", "mike@email.com"}
lisa := &user{"lisa", "lisa@email.com"}

答案1

得分: 1

变量 mike 是一个类型为 user 的变量,而 lisa 是一个指针,类型为 *user

表达式 &user{…} 的意思是 获取一个指向新的 user 对象的指针

英文:

Variable mike is a variable of type user while lisa is a pointer, the type is *user.

Expression &user{…} means take a pointer to a new user object.

答案2

得分: 0

初始化实例用户结构体没有任何区别。在目标变量中访问它有很大的区别。

  1. 情况1,它将用户结构体的值复制到mike变量中。
  2. 情况2,它使用lisa变量引用用户结构体的值。

请看下面的代码片段:

type user struct {
    name  string
    email string
}

someuser := user{"mike", "a@a.com"}
mike := someuser
lisa := &someuser

someuser.name = "hello"
fmt.Println(mike.name)    // name没有改变,因为用户结构体被复制了
fmt.Println(lisa.name)    // name改变了,因为用户结构体被引用了

希望对你有帮助!

英文:

There is no difference in initializing the instance user struct.<br />
There's a big difference in how it is accessed in the target variable.

  1. Case 1, it copies the user struct value into the mike variable
  2. Case 2, it refers the user struct value using the lisa variable

See this snippet:

type user struct {
	name  string
	email string
}

someuser := user{&quot;mike&quot;, &quot;a@a.com&quot;}
mike := someuser
lisa := &amp;someuser

someuser.name = &quot;hello&quot;
fmt.Println(mike.name)    //name is not changed since user struct is copied
fmt.Println(lisa.name)    //name is changed since user struct is referred

huangapple
  • 本文由 发表于 2017年8月12日 21:46:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/45651002.html
匿名

发表评论

匿名网友

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

确定