将数组指针传递给需要类型接口的函数

Golang 书中的一个示例显示了一个指向数组的指针通过引用传递到函数中:


package main


import "fmt"


func reclassify(planets *[]string) {

    *planets = (*planets)[0:8]

}



func main() {

    planets := []string{

        "mercury", "venus", "earth", "mars", "jupiter",

        "saturn", "uranus", "neptune", "pluto",

    }

    reclassify(&planets)

    fmt.Println(planets)

}

我尝试用接口替换 reclassify() 的 *[]string 参数:


func reclassify(planets interface{}) {

    *planets = planets.(*[]string)[0:8]

}

但是我收到这些错误:


./test.go:10:2: invalid indirect of planets (type interface {})

./test.go:10:32: cannot slice planets.(*[]string) (type *[]string)

我之前使用过该接口将不同的数据类型传递给给定的函数。是否可以以类似的方式对此示例进行操作?


我可以看到我的版本的 *planets 变量没有意义,但我不确定将其更改为什么(如果有的话)


尚方宝剑之说
浏览 76回答 1
1回答

慕田峪7331174

我建议使用类型断言来确定类型并更新它。interface在Golang中只是一个接口。func reclassify(planets interface{}) {    switch v := planets.(type) {        case *[]string:            fmt.Println("Slice string:",*v)            *v = (*v)[0:8]        default:            fmt.Println("Uknown")    }}
打开App,查看更多内容
随时随地看视频慕课网APP