dqeznd1697 2016-12-16 03:32
浏览 31
已采纳

关于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)
    }
}
  • 写回答

1条回答 默认 最新

  • douweicheng5532 2016-12-16 03:37
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来