Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Created August 24, 2023 08:59
Show Gist options
  • Save mortymacs/a071e85d02417c8aff5e2c852a0ad52e to your computer and use it in GitHub Desktop.
Save mortymacs/a071e85d02417c8aff5e2c852a0ad52e to your computer and use it in GitHub Desktop.
Check Go data type without using reflect
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