问题
i am getting the error, too few values in struct initialiser at line clusters = append(clusters, Cluster{Point{rand.Float64()}, []Point{}}) the function that throws the error is below.
func initClusters(k int) (clusters []Cluster) {
rand.Seed(time.Now().UnixNano())
for i := 0; i < k; i++ {
clusters = append(clusters, Cluster{Point{rand.Float64()},[]Point{}})
}
return
}
i am putting k = 3, the cluster struct defined is
type Cluster struct {
Center Point
Points []Point
}
and the point is also a struct defined as:
type Point struct {
X float64
Y float64
}
Can someone please help?
回答1:
A struct composite literal must either use named fields or specify all fields. The Point struct has two fields, X and Y. Assuming that you were attempting to set the X field, do one of the following:
Point{X: rand.Float64()} // Y defaults to zero value
Point(X: rand.Float64(), Y: 0} // Y explicitly set to zero using name
Point(rand.Float64(), 0} // Y explicitly set to zero using positional value
Specifying struct fields by name is generally preferred over positional values.
来源:https://stackoverflow.com/questions/54547266/too-few-values-in-struct-intializer-error