关于struct的golang语法问题
问题描述:
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)
}
}
这是一些代码,但是它是如此之长且不必要。 有时我需要向mysql写一些东西,\ nthere是类似的表。 p>
我一直在尝试使用interface {},但它更复杂。 p>
有没有 p>
type一个结构{
ID int
名称字符串
状态布尔值
Devtype字符串
...
创建时间。 时间
}
type两个结构{
ID int
名称字符串
状态布尔值
Devtype字符串
...
创建的时间。时间
}
type三个结构{
Id int
名称字符串
状态布尔值
Devtype字符串
...
创建的时间。时间
}
func Insert(devtype string){
if devtype ==“ one” {
var值一个
值。Id= 1
值。名称=“ device”
值。状态= false
值。Devtype= devtype //仅此一个
值。Created= time.Now()
fmt.Println(value)
}否则,如果devtype = =“ two” {
var value Two
value.Id = 1
value.Name =“ device”
value.Status = false
value.Devtype = devtype //这里只有不同的
值。 创建= time.Now()
fmt.Println(value)
}否则,如果devtype ==“ three” {
var value Three
value.Id = 1
value.Name =“ device”
value.Status = false
value.Devtype = devtype //只有此处是不同的
value.Created = time.Now()
fmt.Println(value)
}
}
code>
div>
答
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