Created
August 24, 2023 08:59
-
-
Save mortymacs/a071e85d02417c8aff5e2c852a0ad52e to your computer and use it in GitHub Desktop.
Check Go data type without using reflect
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 Actioner interface { | |
Delete() string | |
} | |
type User struct { | |
Name string | |
} | |
type Admin struct { | |
Name string | |
} | |
func (User) Delete() string { | |
return "user deleted" | |
} | |
func (Admin) Delete() string { | |
return "admin deleted" | |
} | |
func GetObject() Actioner { | |
return Admin{Name: "test"} | |
} | |
func main() { | |
obj := GetObject() | |
switch obj.(type) { | |
case User: | |
fmt.Println("User action:", obj.(User).Delete()) | |
case Admin: | |
fmt.Println("Admin action:", obj.(Admin).Delete()) | |
default: | |
fmt.Println("unknown type") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment