无法设置结构的属性 [英] Unable to set the property of a struct
问题描述
我正在尝试学习如何在 go 中使用结构体.
I'm trying to learn how to use structs in go.
我有以下包裹
// src/db/db.go
package db
type DB struct {
pk string
}
func (db DB) SetPk(s string) {
db.pk = s
}
func (db DB) GetPk() string {
return db.pk
}
这是我的 main.go
And this is my main.go
package main
import (
"log"
"db"
)
func main() {
d := db.DB{}
d.SetPk("Hello World")
log.Println(d.GetPk())
}
当我运行命令 go run main.go
时,我的命令提示符中出现换行符.我验证了 SetPk 和 GetPk 都被触发,并且 SetPk 正在为 db.pk 分配一个值.但是在 GetPk 被触发的那一刻,db.pk 又是空的.
When I run the command go run main.go
, I get a line break in my command prompt. I verified that both the SetPk and GetPk are being fired, and that the SetPk is assigning a value to db.pk. But the moment GetPk is fired, db.pk is empty again.
如何让db对象保留pk值并在GetPk中返回?
How do I get the db object to retain the pk value and return it in GetPk?
推荐答案
这是因为您需要使方法通过指向变量的指针而不是副本来工作.目前,每种方法仅使用原始副本(空白)来运行该方法.下面就可以了.
It's because you need to make the methods work off of a pointer to the variable and not a copy. Currently each method only uses a copy of the original (which is blank) to run the method. Below will work.
// src/db/db.go
package db
type DB struct {
pk string
}
// Use the pointer back to the object
func (db *DB) SetPk(s string) {
db.pk = s
}
// Use the pointer back to the object
func (db *DB) GetPk() string {
return db.pk
}
这篇关于无法设置结构的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!