Correctly pass struct to function in golang

只谈情不闲聊 提交于 2021-01-01 06:33:43

问题


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:


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



来源:https://stackoverflow.com/questions/24477790/correctly-pass-struct-to-function-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!