我在使用Golang追加到切片時遇到問題。Golang切片附加
這裏是我的代碼:
func MatchBeaconWithXY(w http.ResponseWriter, r *http.Request) ([]types.BeaconDataXY, error) {
context := appengine.NewContext(r)
returnBeaconData := []types.BeaconDataXY{}
beacondata, err := GetBeaconData(w, r)
if err != nil {
log.Errorf(context, "error getting beacondata %v", err)
w.WriteHeader(http.StatusInternalServerError)
return nil, err
}
for index, element := range beacondata {
q := datastore.NewQuery("physicalbeacondata").Filter("NamespaceID =", element.NamespaceID).Filter("InstanceID =", element.InstanceID)
beacondatastatic := []types.BeaconDataStatic{}
_, err := q.GetAll(context, &beacondatastatic)
if err != nil {
log.Errorf(context, "cant get query %v", err)
w.WriteHeader(http.StatusInternalServerError)
return nil, err
}
var beacondataXY = new(types.BeaconDataXY)
beacondataXY.NamespaceID = element.NamespaceID
beacondataXY.InstanceID = element.InstanceID
beacondataXY.XCoord = beacondatastatic[0].XCoord
beacondataXY.YCoord = beacondatastatic[0].YCoord
beacondataXY.Distance = element.Distance
returnBeaconData = append(returnBeaconData, beacondataXY...)
log.Infof(context, "beaondataXY tot %v", beacondataXY)
}
的beacondataxy.go包含此:
package types
type BeaconDataXY struct {
InstanceID string
NamespaceID string
XCoord float64
YCoord float64
Distance float64
}
的錯誤信息是這樣的:
utils.go:139: cannot use beacondataXY (type *types.BeaconDataXY) as type []types.BeaconDataXY in append
我真的不知道如何處理Golang中的切片,即使閱讀了一些使p版本的教程錯誤的感覺。我不確定我做錯了什麼。
我想有一個數組/切片裏面的類型,返回BeaconData是[]類型。 BeaconDataXY,它應該包含單一類型的BeaconDataXY。
感謝您的幫助。
編輯:
現在的代碼如下所示:
func MatchBeaconWithXY(w http.ResponseWriter, r *http.Request) ([]types.BeaconDataXY, error) {
context := appengine.NewContext(r)
//returnBeaconData := []types.BeaconDataXY{}
returnBeaconData := make([]types.BeaconDataXY, 1)
beacondata, err := GetBeaconData(w, r)
if err != nil {
log.Errorf(context, "error getting beacondata %v", err)
w.WriteHeader(http.StatusInternalServerError)
return nil, err
}
for _, element := range beacondata {
q := datastore.NewQuery("physicalbeacondata").Filter("NamespaceID =", element.NamespaceID).Filter("InstanceID =", element.InstanceID)
beacondatastatic := []types.BeaconDataStatic{}
_, err := q.GetAll(context, &beacondatastatic)
if err != nil {
log.Errorf(context, "cant get query %v", err)
w.WriteHeader(http.StatusInternalServerError)
return nil, err
}
var beacondataXY = types.BeaconDataXY{}
beacondataXY.NamespaceID = element.NamespaceID
beacondataXY.InstanceID = element.InstanceID
beacondataXY.XCoord = beacondatastatic[0].XCoord
beacondataXY.YCoord = beacondatastatic[0].YCoord
beacondataXY.Distance = element.Distance
returnBeaconData = append(returnBeaconData, beacondataXY)
//log.Infof(context, "beaondataXY tot %v", beacondataXY)
}
根據那個更新,但仍然是相同的問題,因爲我在另一個解決方案中回答。索引超出範圍 –
請發佈完整的堆棧跟蹤。 – Makkes
如何查看堆棧跟蹤?或者是堆棧跟蹤整個錯誤輸出? http://imgur.com/wMj90Fz –