英文:
Golang: How to use same the method for different structures
问题
我可以将相同的逻辑应用于不同的结构体吗?
例如,更新一个结构体的字段。
我想要在结构体A和B中共享相同的UpdateName
逻辑。
A和B来自不同的包。
// model/A.go
type A struct {
name string
total int64
date time.Time
}
// model/B.go
type B struct {
name string
price float64
total int64
date time.Time
}
希望将重复的逻辑合并为一个。
// service/a.go
func UpdateName(data *A) {
data.Name = "NEW"
}
// service/b.go
func UpdateName(data *B) {
data.Name = "NEW"
}
我想使用接口进行解耦。
此外,如何将接口解析为参数。
type DataSetter interface {
SetName(name string)
SetTotal(total int64)
}
谢谢你帮我解答这个基本问题。
英文:
How can I apply the same logic to different structures?
For example, update a struct's field.
I want to share the same UpdateName
logic for both struct A and B
A and B are from different packages.
// model/A.go
type A struct {
name string
total int64
date time.Time
}
// model/B.go
type B struct {
name string
price float64
total int64
date time.Time
}
Hopefully combine duplicated logic as one.
// service/a.go
func UpdateName(data *A) {
data.Name = "NEW"
}
// service/b.go
func UpdateName(data *B) {
data.Name = "NEW"
}
I'd like to use an interface for decoupling.
Furthermore, How can I parse interface as a parameter.
type DataSetter() interface {
SetName(name string)
SetTotal(total int64)
}
Thanks for helping me with this basic question.
答案1
得分: 2
对于像你展示的简单值赋值,通常最好直接暴露字段:
type A struct {
Name string
...
}
...
func f(a *A) {
a.Name = "x"
}
你可以考虑嵌入一个公共结构体:
type Common struct {
Name string
}
func (c *Common) SetName(s string) {
c.Name = s
}
type A struct {
Common
...
}
type B struct {
Common
...
}
func f(a *A) {
a.SetName("x")
}
你可以使用表示公共类型函数的接口:
type WithName interface {
SetName(string)
}
func f(x WithName) {
x.SetName("x")
}
func g(a *A) {
f(a)
}
func h(b *B) {
f(b)
}
但你不会只为SetName
这个函数这样做。
英文:
For simple value assignments like you showed, it is often better to simply expose the field:
type A struct {
Name string
...
}
...
func f(a *A) {
a.Name="x"
}
You might consider embedding a common struct:
type Common struct {
Name string
}
func (c *Common) SetName(s string) {
c.Name=s
}
type A struct {
Common
...
}
type B struct {
Common
...
}
func f(a *A) {
a.SetName("x")
}
You can use an interface that represents the functions of the common type:
type WithName interface {
SetName(string)
}
func f(x WithName) {
x.SetName("x")
}
func g(a *A) {
f(a)
}
func h(b *B) {
f(b)
}
But you wouldn't want to do this for just SetName
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论