2016-12-16 11 views
0

ここにいくつかのコードがありますが、それはとても長くて不必要です。 時々私はmysqlに何かを書く必要があります。 そのようなテーブルがあります。golang文法についての質問

私はインターフェイス{}を使用しようとしていますが、もっと複雑です。

これを短縮する方法はありますか?

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があるのでし、3種類

+0

を作成することをお勧めではありませんありがとうございました – haroldT