Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

./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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading