1

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?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
ahhmarr
  • 2,296
  • 4
  • 27
  • 30

0 Answers0