Stuct and Interfaces


In the following code,

package main

import "fmt"

type num struct {
	value int

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

type character interface {

func main() {
	var a character = &num{value: 10}

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.

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.


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