Created
August 24, 2023 09:12
-
-
Save mortymacs/02522fe395175a15187c65e7bd92be3e to your computer and use it in GitHub Desktop.
Check Go interface 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
// You can edit this code! | |
// Click here and start typing. | |
package main | |
import "fmt" | |
type Actioner interface { | |
Delete() string | |
} | |
type User struct { | |
Name string | |
} | |
type Admin struct { | |
Name string | |
} | |
type Annoymous struct { | |
Name string | |
} | |
func (User) Delete() string { | |
return "user deleted" | |
} | |
func (Admin) Delete() string { | |
return "admin deleted" | |
} | |
func GetObject() any { | |
return Admin{Name: "test"} | |
} | |
func GetNonActionerObject() any { | |
return Annoymous{Name: "test"} | |
} | |
func main() { | |
// anyObj := GetObject() | |
anyObj := GetNonActionerObject() | |
obj, ok := anyObj.(Actioner) | |
if ok { | |
fmt.Println("Object action:", obj.Delete()) | |
} else { | |
fmt.Println("Object is not actioner!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment