Skip to content

Instantly share code, notes, and snippets.

@gsavovski
Created October 31, 2014 03:30
Show Gist options
  • Select an option

  • Save gsavovski/692c38c656f6b8555dab to your computer and use it in GitHub Desktop.

Select an option

Save gsavovski/692c38c656f6b8555dab to your computer and use it in GitHub Desktop.
Internal struct variables when casting to an interface
// 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