Golang 连接两片指针
Golang concatenate two slices of pointers
在调用 REST API 的 GoLang 程序中,我需要收集来自不同 REST API 的响应,其中 return 相同结构的指针切片。
我正在尝试使用 append 连接指针切片,但出现类似于下图所示的错误。
我认为 append 不支持这样的操作,有什么替代方法吗?
cannot use response (type []*string) as type *string in append
一个 go playground link 的问题,我试图证明这里给出。
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 或函数签名更改为 return 结构切片本身。
要将一个切片的所有元素附加到另一个切片,请使用:
resultSlice=append(slice1, slice2...)
在调用 REST API 的 GoLang 程序中,我需要收集来自不同 REST API 的响应,其中 return 相同结构的指针切片。 我正在尝试使用 append 连接指针切片,但出现类似于下图所示的错误。 我认为 append 不支持这样的操作,有什么替代方法吗?
cannot use response (type []*string) as type *string in append
一个 go playground link 的问题,我试图证明这里给出。 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 或函数签名更改为 return 结构切片本身。
要将一个切片的所有元素附加到另一个切片,请使用:
resultSlice=append(slice1, slice2...)