关于结构的golang语法问题

时间:2016-12-16 03:32:55

标签: go

这里有一些代码,但它太长而且没必要。 有时我需要写一些东西给mysql, 有某种类似的表。

我一直尝试使用interface {},但它更复杂。

有没有办法缩短它?

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 个答案:

答案 0 :(得分:1)

golang的struct inherit将有助于此

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:因为只有一个字段不同,所以创建三种类型

并不是一个好习惯
相关问题