2016-12-16 26 views
0

這裏是一些代碼,但它太長而且沒有必要。 有時我需要寫點東西給mysql, 有這樣的表。有關結構的golang語法問題

我一直嘗試使用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

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 //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:因爲有一個noly領域不同,它不是一個很好的做法,創建三個類型

+0

太謝謝你了 – haroldT