简体   繁体   中英

Too few values in struct intializer error

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM