英文:
I wanna know how this function works
问题
func NewAccount(owner string) *Account {
	account := Account{owner: owner, balance: 0}
	return &account
}
这段代码定义了一个名为NewAccount的函数,它接受一个owner参数,并返回一个指向Account类型的指针。
在函数内部,首先创建了一个名为account的Account结构体实例,其中owner字段被设置为传入的owner参数,balance字段被设置为0。
然后,通过使用&操作符,返回了指向account实例的指针。这样做的目的是为了避免在函数调用时对account进行复制,而是直接返回指向原始实例的指针。这样可以节省内存,并且在函数外部对返回的指针进行操作时,可以修改原始实例的值。
希望这样解释对你有帮助。如果还有其他问题,请随时提问。
英文:
func NewAccount(owner string) *Account {
	account := Account{owner: owner, balance: 0}
	return &account
}
In this code, I wanna know how this function works.
Why did return use '&'? Why did return type use '*'? I wonder how they work.
I googled many times but I didn't find good explains in Korean. So I came here to ask. I got this function's return and return's type are for not copying variable for memory.
答案1
得分: 0
*Account 表示该函数将返回一个指向变量的指针。这个变量必须是 account 类型。
account(小写的 a)是函数作用域内的一个变量。
:= 将其赋值为 Account 的类型和值。
Account 是一个结构体。结构体是一种自定义的数据类型,用于存储其他数据。在这种情况下,Account 包含:owner 和 balance。owner 似乎是指向其所有者的引用,而 balance 是一个数字。
return &account 返回变量 account 的地址。指针是一个变量的地址,因此这满足该函数的返回值。
英文:
*Account means the function will return a pointer to a variable. This variable must be of type account.
account (lowercase 'a') is a variable only within the scope of the function.
:= is assigning it to the type and value of Account.
Account is a struct. A struct is a custom data type which holds other data. In this case, an Account contains: owner and balance. owner seems to be a reference to its owner and balance is a number.
return &account returns the address of the variable account. A pointer is an address of a variable so this satisfies the return value of this function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论