Jeremy covered why it's not working. I think I can answer what the OP wants to do. I think there's a misunderstanding about how interfaces work. I think the OP is trying to give myStruct
the myInterface
interface, but interfaces are implicit.
type myInterface interface {
doFunc() bool
}
This makes an interface myInterface
. Things do not need to be declared to be of an interface. Anything which satisfies the interface is that interface. Anything which defines doFunc() bool
is a myInterface
. There's no need to declare it.
I want that the myValue will be the same for the same objects in the same structure – user1365697 15 mins ago
The idea is to create interface and then to use it from the tests and call to the same method that create the myValue and then send the relevant structure – user1365697 13 mins ago
OP in comment
type myStruct struct {
myValue string
si myInterface
}
This defines a struct which has a string, and it also has something which implements myInterface
. Again, that's anything which defines doFunc() bool
.
It's important to realize that myStruct.si
is a totally different thing with (potentially, because it's not defined) its own myValue
.
Instead of giving myStruct
its own extra struct, I think what the OP intended is to give myStruct
the myInterface
interface. Since interfaces are implicit myStruct
already satisfies myInterface
. It should look like this:
package main
import (
"fmt"
)
type myInterface interface {
doFunc() bool
}
type myStruct struct {
myValue string
}
func (s myStruct) doMyLogic() bool {
fmt.Println(s.myValue)
s.doFunc()
return false
}
func (s myStruct) doFunc() bool {
fmt.Println(s.myValue)
return false
}
func main() {
myS := myStruct{ myValue: "test" }
if myS.doMyLogic() {
return
}
}
Because myStruct
has doFunc() bool
defined it satisfies the myInterface
interface. There's no need to add an extra field for it.
You can pass myStruct
to anything requiring myInterface
. That's the idea behind interfaces. Rather than making explicit declarations, anything which satisfies the interface will work. Like Duck Typing, but strict.
func usesMyInterface(s myInterface) bool {
return s.doFunc()
}
func main() {
myS := myStruct{ myValue: "test" }
usesMyInterface(myS)
}