How to call functions in interface

calling.go file in str folder

package str

import "str/into"

type DA struct {
	aa string
	bb into.Con
}

func Ring(a string) *DA {
	c := into.Open(a)
	d := c.Db()
	da := &DA{
		aa: d,
		bb: c,
	}
	return da
}

interface.go file in str/into

package into

//Named is an interface with open function
type Named interface {
	Open(name string) Con
}

//Con is an interface with db function
type Con interface {
	Db() string
}

But the error is in the calling.go file that the into.Open function is undefined. But other package will have the defination of this function.

Like how the database/sql/driver/driver.go is defined by the other packages.

implement.go this implements the functions in the interface.go

package implement

import (
	"str/into"
)

type Con struct {
	str1 string
	len1 int
}

func Open(a string) into.Con {
	d := len(a)
	return &Con{str1: a, len1: d}
}

func (c *Con) Db() string {
	str2 := "Akhil" + c.str1
	return str2
}

Thanks

You need to implement into.Named.Open() for a datatype of yours and then call the method on a value of that type:

https://play.golang.org/p/B1uk7bkfwSG

PS: You are doing it already correctly for your implement.Con as it seems.

type Named struct {
}

func (n *Named) Open(a string) into.Con {
	d := len(a)
	return &Con{str1: a, len1: d}
}

If i declare like this then I have to call the Open functionlike into.Named.Open , But I want it to be called by into.Open like how i called str.Ring()

can we call like that?

And when I declare it and tried to run the code it produces the error like

# str
C:\Go\src\str\calling.go:11:22: not enough arguments in call to method expression into.Named.Open
        have (string)
        want (into.Named, string)

Then you can’t make it an interface.

Ok. Then why the above code is producing an error. The code which you told. Is there any mistake I did.

You are not calling the method on a value, but you call it as a function, therefore you need to provide the value that you usually call the method on, as the first argument to the function call.

If I pass into.Named as an argument then I have to change my Open func defination or not.

Sorry I am not able to understand it,Can you explain me in detail

Thanks

I’m not sure if I even understand your problem, so I’m pretty sure I can not explain it any better than I did.

Therefore I suggest doing the tour on interfaces and methods.

Thanks @NobbZ I am able to solve it.

Before Calling the Open function I have to create an obj for the Named Struct and pass using init function and then use the passed struct object to call the Open function.

Thanks.

As I have said multiple times, you need a value of a type that implements the method.

Yes, Now everything Make Sense. Sorry I was thinking in the wrong direction.

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