Worlock
Worlock

Reputation: 446

Understanding Interface

I am a newbie in Go lang , I was trying to understand Go Interface by writing a simple piece of code . I am getting an error , as I am not able to understand the correct way of referring to a Interface method kindly tell me where I am going wrong.

type Info interface {
Noofchar() int
}

type Testinfo struct {
noofchar int
}

func (x Testinfo)Noofchar() int {
return x.noofchar
}

func main(){
var t Info
fmt.Println(x.Testinfo)
fmt.Println("No of char ",t.Noofchar())
x.noofchar++
fmt.Println("No of char ",t.Noofchar())
}

Am I referring to the method correctly by t.Noofchar() ? or there is something else that I am missing

Upvotes: 2

Views: 201

Answers (2)

Daniel
Daniel

Reputation: 38771

Methods typically receive pointers to a struct.

func (x Testinfo)Noofchar() int {

changed to

func (x *Testinfo)Noofchar() int {

Took out var x Info in the beginning, refactored your main() just a bit and the resulting code in play is:

package main

import "fmt"

type Info interface {
    Noofchar() int
    Increment()
}

type Testinfo struct {
    noofchar int
}

func (x *Testinfo) Noofchar() int {
    return x.noofchar
}
func (x *Testinfo) Increment() {
    x.noofchar++
}

func main(){
    var t Info = &Testinfo{noofchar:1}
    fmt.Println("No of char ",t.Noofchar())
    t.Increment()
    fmt.Println("No of char ",t.Noofchar())
}

http://play.golang.org/p/6D-LzzYYMU

In your example you modify x directly. If you're passing an interface around, you don't have access to the underlying data structures, only the methods. So I changed your direct increment to an Increment() method.

Upvotes: 3

the system
the system

Reputation: 9336

x is a variable to which you can assign anything that implements the Info interface. You've assigned nothing to that variable.

Once you assign something, x.noofchar++ will not work because again x can hold anything that implements the Info interface, which means you can only access the methods defined by that interface. Interfaces do not allow direct access to fields.

The only method defined in the Info interface is the Noofchar() int method, so that is the only way to interact with the value stored in x.

The x defined by the method receiver (x Testinfo) isn't at all related to the var x Info variable. That x does have direct access to the struct fields.

The t.Noofchar() calls are correct and will work.

Upvotes: 1

Related Questions