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.

1
  • Try to create newConnection without the ampersand (&) operator. Does that help? Commented Jun 29, 2014 at 16:50

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This answer seems correct. I wonder, why it hasn't been accepted yet

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.