The project structure requires to define interface and implementations in separate files.
It's best to download a small isolated test case to get a picture, but here's the code too. It's a library project that's why mylib
is declared as package for each file. I wanted to have subpackages but golang doesn't allow that, so instead I put everything under one package while files are in separate directories.
src/interfaces/my_interface.go
package mylib
type MyInterface interface {
foo()
bar()
}
src/interfaces/my_implementation.go how to import interface here?
package mylib
type MyImplementation struct {}
// possible to declare *MyInteface here?
func (imp *MyImplementation) foo() {}
func (imp *MyImplementation) bar() {}
test/implementations/implementation_test.go
package implementations
import (
"testing"
"fmt"
"implementations"
mylib2 "interfaces" // why mylib2 here?
)
func TestImplementation(t *testing.T) {
// how to declare variable of type `MyInterface` and assign an object `MyImplementation` to it
interface_type_var := mylib2.MyInterface() // error
interface_type_var := mylib.MyImplementation{} // error
fmt.Println("Test successful")
}
Question
How can I declare a type of MyInterface and assign object of MyImplementation to it.
how to import and interface in the implementation file
Autocomplete of IDE put this under imports automatically as I was importing interface type. not sure why. mylib2 "interfaces"
. i learned it's an alias but why do we need alias here?
Help fix the code in the implementation_test
please
You have already declared a type of MyInterface
inside src/interfaces/my_interface.go
. You don't have to redeclare it and you don't have to explicitly assign MyImplementation
to the interface. All you have to make sure is that your MyImplementation
implements all the methods from the interface. As long as both files are in the same package and same folder level, your implementation automatically becomes your interface.
As long they are both in the same package and folder you do not have to import interface inside implementation
At time of this writing Gogland is in Early Access Program which is just another name for BETA :). I don't think SO allows commenting on anything in beta. Sorry.
EDIT
~/go
. You need a structure like this: ~/go/src/github.com/user/mylib
. So if you want a subfolder/subpackage you would have something like this ~/go/src/github.com/user/mylib/util
and util would be its own package. It's wrong to try to have Implementations in one folder and interfaces in another. Rather group them logically and create subpackages. Then in your test you can use them like this:import(
"github.com/user/mylib"
"github.com/user/mylib/util"
)
github.com or any other repo service is important specially if you are writing library that is suppose to be reusable in any project.
Besides that, I'd suggest to use more stable IDE or editor.
Hope this helps