Stuct and Interfaces

Hi,

In the following code,

package main

import "fmt"

type num struct {
	value int
}

func (n *num) change() {
	n.value = 20
}

type character interface {
	change()
}

func main() {
	var a character = &num{value: 10}
	a.change()
	fmt.Println(a)
}

I have initialized a variable a as an interface of type num. Now a.value = 20 doesn’t work. In order to change the value of a, should it be done only through the method change()?

Any help is appreciated. I’m just learning interfaces. Thanks.

Regards,
Gokul PM

With a declared as character, you can’t access it as the concrete implementation type num. If you must, you can use a type assertion to get to the underlying type, but since you are working with an interface, you really should code to the interface.

2 Likes

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