Created
October 31, 2014 03:30
-
-
Save gsavovski/692c38c656f6b8555dab to your computer and use it in GitHub Desktop.
Internal struct variables when casting to an interface
This file contains hidden or 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
| // Variables accesible directly on the structure | |
| // but after casted to a interface, still accesible | |
| // for the implementing methods thought | |
| package main | |
| import "fmt" | |
| type Animal interface{ | |
| Speak() string | |
| Walk() string | |
| } | |
| type Cat struct{} | |
| func (c *Cat)Speak() string { | |
| return "Miau" | |
| } | |
| func (c *Cat) Walk() string{ | |
| return "Kittie walk" | |
| } | |
| type Cat1 struct{ | |
| specialty string | |
| } | |
| func (c *Cat1) Speak() string{ | |
| s := "Speaking " + c.specialty | |
| return s | |
| } | |
| func (c *Cat1) Walk() string{ | |
| s := "Walking " + c.specialty | |
| return s | |
| } | |
| func main() { | |
| c := &Cat{} | |
| fmt.Println(c.Speak()) | |
| fmt.Println(c.Walk()) | |
| c1 := &Cat1{"especially for you"} | |
| fmt.Println("Specialty", c1.specialty) | |
| g := Animal(c1) | |
| fmt.Println("Cat casted to Animal", g.Speak()) | |
| fmt.Println("Specialty", g.specialty) //g.specialty undefined (type Animal has no field or method specialty) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment