2

I have a golang structure:

type Connection struct {
    Write chan []byte
    Quit chan bool
}

I'm creating it with:

newConnection := &Connection{make(chan []byte), make(chan bool)}

How to correctly create functional type with Connection parameter and function of this type?

I mean that i want to do something like this:

type Handler func(string, Connection)

and

handler(line, newConnection)

whene handler is:

func handler(input string, conn tcp.Connection) {}

cannot use newConnection (type *Connection) as type Connection in argument to handler

Thank you.

0xAX
  • 20,957
  • 26
  • 117
  • 206
  • Try to create newConnection without the ampersand (&) operator. Does that help? – fuz Jun 29 '14 at 16:50

1 Answers1

5

the Problem is that the type of Handler is Connection and the value that you are passing is of type *Connection, i.e. Pointer-to-Connection.

Change the handler definition to be of type *Connection

Here is a working Example:

package main

import "fmt"

type Connection struct {
    Write chan []byte
    Quit  chan bool
}

type Handler func(string, *Connection)

func main() {
    var myHandler Handler

    myHandler = func(name string, conn *Connection) {
        fmt.Println("Connected!")
    }

    newConnection := &Connection{make(chan []byte), make(chan bool)}

    myHandler("input", newConnection)

}

https://play.golang.org/p/8H2FocX5U9

fabrizioM
  • 46,639
  • 15
  • 102
  • 119