How do I convert the type of an anonymous single slice struct?

58 Views Asked by At

I want to type convert an input to specific struct type, however in a particular scenario the conversion fails. It happens when I have a single item from a slice which I want to convert to a specific type. I have added a basic example below to demonstrate the panic/error.

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)
}

The error:

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

In the above situation it does not make sense to convert the employee back to a specific type as print can accept any type, however I did this to demonstrate the error. Any idea how I can convert the interface type of employee in PrintEmployeeDetails back to a typed struct?

1

There are 1 best solutions below

0
tombraider On

As the error suggests, you're trying to type convert a struct (i.e. struct{name, surname...}) to a slice of struct (i.e. Employee = []struct{name, surname...})

Either you need to change Employee from a named type to a struct or fix the PrintEmployeeDetails function to type convert to the struct you need explicitly.