How to get the property if an interface object?

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)

}

Are you looking for this ?
fmt.Println(iCat.(Cat).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.

Playground example off your provided code: https://play.golang.org/p/EHCf69U5bfk
Article with examples: https://gobyexample.com/interfaces
Tour of Go Section: https://tour.golang.org/methods/10

1 Like

Yes I understand you can do it with some “getter” methods. But I am trying to understand Go. So the answer from Ivan is what I am looking for.

Can you parse that out? Why are the paren (Cat) significant. I had of course tried it without paren. iCat.Cat.Weight

Thanks!

Can you explain why you would ever create an explicit instance of an interface object? What this would be used for in a pattern or something?

Hi,

It’s called type assertion. You can have a good introduction on this subject here : https://tour.golang.org/methods/15

Hi Ivan, sorry for pushing this, but now how do we write back into it?

This doesn’t work.

iCat.(Cat).Weight = iCat.(Cat).Weight + 1

Thanks!

Simply like this:

c := iCat.(Cat)
c.Weight += 1
fmt.Println(c.Weight)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.