英文:
golang grammar questions about struct
问题
这里有一些代码,但是它很长而且不必要。有时我需要将一些东西写入到MySQL中,有一些类似的表格。
我一直在尝试使用interface{},但它更加复杂。
有没有办法让它更短一些?
type Device struct {
Id int
Name string
Status bool
Devtype string
// ...
Created time.Time
}
func Insert(devtype string) {
var value Device
value.Id = 1
value.Name = "device"
value.Status = false
value.Devtype = devtype
value.Created = time.Now()
fmt.Println(value)
}
你可以将One
、Two
和Three
类型合并为一个名为Device
的结构体类型。然后,在Insert
函数中,只需创建一个Device
变量,并根据devtype
的值设置Devtype
字段的不同值。这样可以减少重复的代码,并使代码更简洁。
英文:
here is some codes, but it is so long and unnecessary.
Sometimes I need to write somethings to mysql,
there is some kind of tables like that.
I have been try to use interface{}, but it is more complex.
Is there any way to make it shorter?
type One struct{
Id int
Name String
Status bool
Devtype string
...
Created time.Time
}
type Two struct{
Id int
Name String
Status bool
Devtype string
...
Created time.Time
}
type Three struct{
Id int
Name String
Status bool
Devtype string
...
Created time.Time
}
func Insert(devtype string){
if devtype == "one"{
var value One
value.Id = 1
value.Name = "device"
value.Status = false
value.Devtype = devtype //only here is different
value.Created = time.Now()
fmt.Println(value)
}else if devtype == "two"{
var value Two
value.Id = 1
value.Name = "device"
value.Status = false
value.Devtype = devtype //only here is different
value.Created = time.Now()
fmt.Println(value)
}else if devtype == "three"{
var value Three
value.Id = 1
value.Name = "device"
value.Status = false
value.Devtype = devtype //only here is different
value.Created = time.Now()
fmt.Println(value)
}
}
答案1
得分: 1
golang的结构体继承可以帮助实现这个需求。
type Base struct {
Id int
Name string
Status bool
...
Created time.Time
}
type One struct{
Base
Devtype string
}
type Two struct{
Base
Devtype string
}
type Three struct{
Base
Devtype string
}
func Insert(devtype string, base Base){
switch devtype {
case "one":
var value One
value.Base = base
value.Devtype = devtype //只有这里不同
case "two":
var value Two
value.Base = base
value.Devtype = devtype //只有这里不同
case "three":
var value Three
value.Base = base
value.Devtype = devtype //只有这里不同
}
}
注意:由于只有一个字段不同,创建三个类型并不是一个好的做法。
英文:
golang's struct inherit will help this
type Base struct {
Id int
Name String
Status bool
...
Created time.Time
}
type One struct{
Base
Devtype string
}
type Two struct{
Base
Devtype string
}
type Three struct{
Base
Devtype string
}
func Insert(devtype string, base Base){
switch devtype {
case "one"
var value One
value.Base = base
value.Devtype = devtype //only here is different
case "two"
var value Two
value.Base = base
value.Devtype = devtype //only here is different
case "three"
var value Three
value.Base = base
value.Devtype = devtype //only here is different
}
}
PS: since there is noly one field different, it is not a good practice to create three type
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论