如何转换匿名单切片结构的类型?

问题描述 投票:0回答:1

我想将输入类型转换为特定的结构类型,但是在特定情况下转换失败。当我想要将切片中的单个项目转换为特定类型时,就会发生这种情况。我在下面添加了一个基本示例来演示恐慌/错误。

package main

import "fmt"

type Employee = []struct{
    name string
    surname string
    age int
    role string
}

func main() {
    em := Employee{{
        name: "John",
        surname: "Johnson",
        age: 40,
        role: "software developer",
    }}

    PrintEmployeeDetails(em[0])
}

func PrintEmployeeDetails(employee interface{}) {
    em := employee.(Employee)
    fmt.Print(em)
}

错误:

panic: interface conversion: interface {} is struct { name string; surname string; age int; role string }, not [][]struct { name string; surname string; age int; role string }

在上述情况下,将员工转换回特定类型是没有意义的,因为 print 可以接受任何类型,但我这样做是为了演示错误。知道如何将 PrintEmployeeDetails 中员工的接口类型转换回类型结构吗?

go struct slice literals
1个回答
0
投票

正如错误所示,您正在尝试将结构体(即 struct{name, surname...})类型转换为结构体切片(即 Employee = []struct{name, surname...})

您需要将 Employee 从命名类型更改为结构体,或者修复

PrintEmployeeDetails
函数以将类型转换为您显式需要的结构体。

© www.soinside.com 2019 - 2024. All rights reserved.