我有一个golang结构:
type Connection struct {
Write chan []byte
Quit chan bool
}
我用以下方式创建它:
newConnection := &Connection{make(chan []byte), make(chan bool)}
如何使用此类型的Connection参数和函数正确创建功能类型?
我的意思是我想做这样的事情:
type Handler func(string, Connection)
和
handler(line, newConnection)
当handler
是:
func handler(input string, conn tcp.Connection) {}
cannot use newConnection (type *Connection) as type Connection in argument to handler
谢谢。
答案 0 :(得分:2)
问题是Handler
的类型是Connection
,而您传递的值是*Connection
类型,即指向连接的指针。
将处理程序定义更改为* Connection
类型这是一个有效的例子:
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)
}