Reputation: 153
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)
}
}
Upvotes: 0
Views: 95
Reputation: 2544
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
Upvotes: 1