Go语言 如何将[]接口转换为[]结构[duplicate]

7gyucuyw  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(127)

此问题在此处已有答案

How do I convert from a slice of interface{} to a slice of my struct type in Go? [duplicate](2个答案)
Type converting slices of interfaces(9个答案)
去年关闭了。
例如,以下代码:

type person struct { //struct
  id   int
  name string
}

func example()  {
  var (
      p []person
      pi []interface{}
  )
  pi = append(pi, person{
      id:   1,
      name: "Mike",
  })
}

如何将pi转换为p

wz1wpwve

wz1wpwve1#

试试这个:

package main

import (
    "fmt"
)

type person struct { //struct
    id   int
    name string
}

func main() {
    var (
        p  []person
        pi []interface{}
    )
    pi = append(pi, person{
        id:   1,
        name: "Mike",
    })
    for _, tmp := range pi {
         // fmt.Println(tmp,k)
         p = append(p, tmp.(person))
         fmt.Println( p)
    }

}

相关问题