【发布时间】: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 给出的建议。可以帮助错过这个爆炸切片方法的人。