【问题标题】:Golang concatenate two slices of pointers [closed]Golang连接两片指针[关闭]
【发布时间】:2021-06-13 21:41:13
【问题描述】:

在调用 REST API 的 GoLang 程序中,我需要收集来自不同 REST API 的响应,这些响应返回相同结构的指针切片。 我正在尝试使用 append 连接指针切片,我收到类似于下面显示的错误。 我认为 append 不支持这样的操作,有什么替代方法吗?

cannot use response (type []*string) as type *string in append

这里给出了我试图演示的问题的 go playground 链接。 https://play.golang.org/p/lnzSd2kbht0

package main

import (
    "fmt"
)

func main() {
    var fruits []*string

    response := GetStrings("Apple")
    fruits = append(fruits, response...)
    response = GetStrings("Banana")
    fruits = append(fruits, response...)
    response = GetStrings("Orange")
    fruits = append(fruits, response...)

    if fruits == nil || len(fruits) == 0 {
        fmt.Printf("Nil Slice")
    } else {
        fmt.Printf("Non nil")
        fmt.Printf("%v", fruits)
    }

}

func GetStrings(input string) []*string {
    var myslice []*string
    myslice = append(myslice, &input)
    return myslice
}

我无法更改 REST API 或函数签名以返回结构切片本身。

【问题讨论】:

  • 我已经添加了内联代码以及 Burak 给出的建议。可以帮助错过这个爆炸切片方法的人。

标签: go pointers slice


【解决方案1】:

要将切片的所有元素附加到另一个切片,请使用:

resultSlice=append(slice1, slice2...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2013-12-28
    • 2021-12-16
    • 1970-01-01
    相关资源
    最近更新 更多