英文:
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,它将用户结构体的值复制到mike变量中。
- 情况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.
- Case 1, it copies the user struct value into the mike variable
- Case 2, it refers the user struct value using the lisa variable
See this snippet:
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 is not changed since user struct is copied
fmt.Println(lisa.name) //name is changed since user struct is referred
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论