2016-11-03 47 views
2

这是对类似文章的轻微改动。在结构中初始化一个结构体

我有一个叫data包,有以下几点:

type CityCoords struct { 
    Name string 
    Lat float64 
    Long float64 
} 

type Country struct { 
     Name string 
     Capitol *CityCoords 
} 

在我的主要功能我尝试初始化一个国家像这样:

germany := data.Country { 
    Name: "Germany", 
    Capitol: { 
     Name: "Berlin", //error is on this line 
     Lat: 52.5200, 
     Long: 13.4050, 
    }, 

} 

当我建立我的项目,我得到这个错误与“姓名”对应,因为我已经标记为上面:

missing type in composite literal 

如何解决此错误?

回答

3

据了解,*意味着一个对象指针是预期的。所以,你可以先使用&来启动它;

func main() { 
    germany := &data.Country{ 
     Name: "Germany", 
     Capitol: &data.CityCoords{ 
      Name: "Berlin", //error is on this line 
      Lat: 52.5200, 
      Long: 13.4050, 
     }, 
    } 
    fmt.Printf("%#v\n", germany) 
} 

或者,您可以选择更优雅的方式;

// data.go 
package data 

type Country struct { 
    Name string 
    Capital *CountryCapital 
} 

type CountryCapital struct { 
    Name string 
    Lat  float64 
    Lon  float64 
} 

func NewCountry(name string, capital *CountryCapital) *Country { 
    // note: all properties must be in the same range 
    return &Country{name, capital} 
} 

func NewCountryCapital(name string, lat, lon float64) *CountryCapital { 
    // note: all properties must be in the same range 
    return &CountryCapital{name, lat, lon} 
} 

// main.go 
func main() { 
    c := data.NewCountry("Germany", data.NewCountryCapital("Berlin", 52.5200, 13.4050)) 
    fmt.Printf("%#v\n", c) 
} 
+0

谢谢,K-Gun。你为什么要从NewCountry和NewCountryCapital返回指向Country和CountryCapital的指针? –

+0

没有具体的理由要做到这一点,您可以根据需要命名该功能。但我认为,在Go世界中,这是一个广泛使用的约定,因为没有'new'关键字来初始化像其他语言中的对象。因此,[Gophers](https://blog.golang.org/gopher)更喜欢用'New'前缀命名函数,并且据我看到它使得它们的代码更具可读性,也更具语义性。 –