go - Cannot use some type in function call -
currently, i'm having 2 files in 2 packages.
file somepkg/something.go
package somepkg // ---------------------------------------------------------------------------- // interfaces // ---------------------------------------------------------------------------- type interface { // other methods handle(handler *handler) } type somethingimpl struct { handlers []handler } type handler interface { incomingcall(request *incomingrequest) } // ---------------------------------------------------------------------------- // somethingimpl implementation // ---------------------------------------------------------------------------- func newsomething() { u := new(somethingimpl) // more operations u return u } func (l *somethingimpl) handle(handler *handler) { fmt.printf("handler: %s", handler) } file main.go
package main import ( "fmt" ) type myhandler struct {} func (h *myhandler) incomingcall(request *somepkg.incomingrequest) { fmt.printf("handler!") } func main() { mysomething := somepkg.newsomething() handler := new(myhandler) // works far. mysomething.handle(handler) // <-- here compilation error occurs } trying run go build yields following compilation error:
{...}\main.go:20: cannot use handler (type *myhandler) type *somepkg.handler in argument mysomething.handle: *somepkg.handler pointer interface, not interface whereas main.go:20 refers line above i'm calling mysomething.handle(handler).
actually, both myhandler , somepkg.handler seem pointers. both of them implement same methods.
why compiler not consider these types compatible ?
you have method;
func (l *somethingimpl) handle(handler *handler) { fmt.printf("handler: %s", handler) } defined take interface pointer not want. you're looking have *myhandler implement handler interface rather myhandler (or both could) can pass reference type method.
//new method sig handle(handler handler) // preferred syntax assignment here handler := &myhandler{} // works fine mysomething.handle(handler) if want keep method sig how have it, make code work need mysomething.handle(&handler) i'm doubtful that's want do.
btw; in code *myhandler implementing interface due method func (h *myhandler) incomingcall(request *somepkg.incomingrequest) haveing *myhandler receiving type apposed func (h myhandler) make myhandler implements handler interface. little go nuance recievers , interfaces there.
Comments
Post a Comment