Here is the code. I am trying to get the Weight of the cat using the iCat object. The last commented line is fails. Does the interface not provide the assigned type values?
prog.go:34:18: iCat.Weight undefined (type Animal has no field or method Weight)
But I did assign Cat to the Animal interface.
package main
import (
"fmt"
"reflect"
)
type Animal interface {
Speak() string
}
type Cat struct {
Color string
Weight int
}
func (c Cat) Speak() string {
return "Meow!"
}
func main() {
iCat := Animal(Cat{"brown", 20},)
fmt.Println(reflect.TypeOf(iCat))
sCat := Cat{"brown", 20}
// Here you see the values of both iCat and sCat
fmt.Println(iCat.Speak(), iCat, sCat)
// How do I get the weight of the Cat thru the interface object
// fmt.Println(iCat.Weight)
}
I do not understand why you are trying to do that with interfaces in the first place, as it is by far the wrong way to use interfaces in Go. The idea is to write functions with generic uses for objects that meet a signature of methods, not to create instances of some kind of wrapping that isn’t actually extending anything. Interfaces only know about methods, they don’t know about variables.