How to implement setter for exported field in Golang?

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

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.

huangapple
  • 本文由 发表于 2017年7月11日 13:09:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/45025850.html
匿名

发表评论

匿名网友

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

确定