Last active
July 8, 2020 09:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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