Golang切片追加

huangapple go评论118阅读模式
英文:

Golang slices append

问题

我在使用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中的切片,即使阅读了一些非常清晰的教程。我不确定我做错了什么。

我想要一个包含类型为[]types.BeaconDataXY的数组/切片,返回的BeaconData应该包含单个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)
    }

希望能对您有所帮助。

英文:

I am having a problem when appending to my slice using Golang.

Here is my code:

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)
}

The beacondataxy.go contains this:

package types

type BeaconDataXY struct {
	InstanceID  string
	NamespaceID string
	XCoord      float64
	YCoord      float64
	Distance    float64
}

The error message is this:

> utils.go:139: cannot use beacondataXY (type *types.BeaconDataXY) as
> type []types.BeaconDataXY in append

I don't really know how to handle slices in Golang, even after reading some tutorials that makes perfect sense. I'm not sure what I'm doing wrong.

I want to have an array/slice with types inside, return BeaconData is of []types. BeaconDataXY and it should contain single types of BeaconDataXY.

Thanks for all help.

EDIT:

The code now looks like this:

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)
	}

答案1

得分: 3

通过这个赋值语句:

var beacondataXY = new(types.BeaconDataXY)

你创建了一个类型为*types.BeaconDataXY的变量。你可以像这样创建一个新的BeaconDataXY:

var beacondataXY = types.BeaconDataXY{}

当向数组追加元素时,可以这样做:

returnBeaconData = append(returnBeaconData, beacondataXY)

省略号"..."假设beacondataXY是一个数组,但实际上它不是,你只是想将beacondataXY追加到returnBeaconData中。请参考https://golang.org/ref/spec#Appending_and_copying_slices,了解在这个上下文中省略号"..."的含义。

英文:

With this assignment:

var beacondataXY = new(types.BeaconDataXY)

you are creating a variable of type *types.BeaconDataXY. Just create a new BeaconDataXY like this:

var beacondataXY = types.BeaconDataXY{}

When appending to your array do it like this:

returnBeaconData = append(returnBeaconData, beacondataXY)

The "..." would assume that beacondataXY is an array but it isn't, you just want to append beacondataXY to returnBeaconData. See https://golang.org/ref/spec#Appending_and_copying_slices for an explanation of what "..." means in this context.

答案2

得分: 1

尝试使用returnBeaconData = append(returnBeaconData, *beacondataXY)

new()内置函数返回一个指针,你也可以使用以下方式替代:

var beacondataXY = types.BeaconDataXY{}

英文:

Try returnBeaconData = append(returnBeaconData, *beacondataXY)

new() built-in function returns a pointer, you can alternatively write:

var beacondataXY = types.BeaconDataXY{}

huangapple
  • 本文由 发表于 2017年1月31日 22:09:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/41959651.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定