Too few values in struct intializer error

别等时光非礼了梦想. 提交于 2021-02-17 07:22:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!