How to access child type's properties in object of parent type in Go?

I am creating a file storage. I am trying to create different types of files. To simulate this, I use the code:

package main

import (
    "fmt"
    "time"
)

type File interface{}

type Audio struct {
    File
    Duration time.Duration
}

type Image struct {
    File
    Width  uint
    Height uint
}

func main() {
    var files = map[string]File{
        "1": Audio{
            Duration: 14 * time.Second,
        },
        "2": Image{
            Height: 9989,
            Width:  1111,
        },
        "3": Image{
                        Width:  1234,
            Height: 5678,
        },
    }
    for k, v := range files {
        switch v.(type) {
        case Audio:
            fmt.Printf("%s: Audio %d seconds", k, v.Duration / time.Second)
        case Image:
            fmt.Printf("%s: Image %dx%d", k, v.Width, v.Height)
        }
    }
}

I am expecting this output:

1: Audio 14 seconds
2: Image 1111x9989
3: Image 1234x5678

But Go compiler gives me this error:

./main.go:38:44: v.Duration undefined (type File has no field or method Duration)
./main.go:40:39: v.Width undefined (type File has no field or method Width)
./main.go:40:48: v.Height undefined (type File has no field or method Height)

How to fix the error?

>Solution :

switch v := v.(type) {

Will declare a new v with the type you are expecting.

Leave a Reply