0xAX
0xAX

Reputation: 21837

Correctly pass struct to function in golang

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.

Upvotes: 2

Views: 11776

Answers (1)

fabmilo
fabmilo

Reputation: 48330

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

Upvotes: 5

Related Questions