access struct properties which are passed as generic in a golang function

Viewed 28

New to golang & generic

example code

package main

import (
    "fmt"
)

type First struct {
    Id          string
    Info        string
    Coordinates map[string]string
}

type Second struct {
    Id      string
    Info    string
    Address string
}

func ping[K First | Second](arg K) {
    fmt.Printf("%v", arg.Info)
}

func main() {
    ping(Second{
        Id:      "ue18",
        Info:    "some info",
        Address: "some address",
    })

}

https://goplay.tools/snippet/KykUh9Hb4Xc

have error like arg.Info undefined (type K has no field or method Info)

I understood the reason behind the compiler error (the requested field might not be available in some cases)

would it be possible to access specific Struct properties safely?

0 Answers
Related