Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/e54d77099dd99f53ed8761883277f066 to your computer and use it in GitHub Desktop.
Save Integralist/e54d77099dd99f53ed8761883277f066 to your computer and use it in GitHub Desktop.
[golang check if struct is a specific type] #go #golang #struct #type #assert #check
package main
import "fmt"
type Test struct {
foo int
}
type TestA struct {
Test
}
type TestB struct {
Test
}
func isTest(t interface{}) string {
switch t.(type) {
case TestA:
return "A"
case TestB:
return "B"
default:
return "NA"
}
}
func main() {
ta := TestA{}
tb := TestB{}
// by not setting 'foo' property as part of TestA/TestB instantiation
// we avoid the "cannot use promoted field" compiler error
// see: https://gist.github.com/Integralist/b123e4a98bcf232d09216577c29f34a3
ta.foo = 1
tb.foo = 2
/*
a better approach to avoid the "cannot use promoted field" compiler error
would be to do this...
t := Test{foo: 123}
ta := TestA{t}
tb := TestB{t}
*/
fmt.Printf("%+v\n", ta)
fmt.Printf("%+v\n", tb)
fmt.Println(isTest(ta)) // A
fmt.Println(isTest(tb)) // B
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment