英文:
How to implement setter for exported field in Golang?
问题
我正在使用gorm
库,为了使用该库,我必须导出所有列字段。就像这样:
type myType struct {
Id int
Name string
}
但是,如果我想要为结构字段添加额外的逻辑怎么办?比如说,如果我想要在Name
字段前加上Mr
前缀怎么办?客户端总是可以这样做:myType.Name = "whatever"
。如果我将Name
设置为未导出并为其设置setter,那么该字段将无法与gorm
一起使用。有没有一种符合Go语言规范的方法来处理这个问题?
英文:
I'm using gorm
lib and to use that lib, I have to export all column fields. Something like this
type myType struct {
Id int
Name string
}
But with that, how to I deal with addition logics for struct fields. Let's say, what if I want to prefix Mr
to the Name
field? The client can always do myType.Name = "whatever"
. If I make Name
to be unexported and have setter for it, that field will never work with gorm
. Any golang-way to deal with this?
答案1
得分: 2
你对于未导出字段与方法的理解是正确的。
你的struct
字段必须是导出的,这样gorm
才能访问它。这是Go的方式。
所以你有两个选项。
选项1:利用gorm回调AfterFind。基本上,你的结构体必须实现这个回调函数。在查询之后,你需要更新Name
字段。
选项2:作为数据获取方法的一部分实现。在返回给调用者之前,更新Name
字段。
英文:
Your understanding is correct about unexported field with method.
Your struct
Fields have to be exported then only gorm
will have access to it. That is Go way.
So you have 2 options.
Option 1: taking advantage of gorm callback AfterFind. Basically your struct have to implement this callback. After find you have to update the field Name
.
Option 2: Implement as part of your data fetch method. Update the field Name
before returning to the caller.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论