本文介绍了正确地传递结构以在golang中起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个golang结构:
I have a golang structure:
type Connection struct {
Write chan []byte
Quit chan bool
}
我用以下方法创建它:
newConnection := &Connection{make(chan []byte), make(chan bool)}
如何使用Connection参数和该类型的函数正确创建函数类型?
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)
和
handler(line, newConnection)
handler
是的时候
func handler(input string, conn tcp.Connection) {}
cannot use newConnection (type *Connection) as type Connection in argument to handler
谢谢.
推荐答案
问题是 Handler
的类型是 Connection
,而您传递的值是输入 * Connection
,即Pointer-to-Connection.
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.
将处理程序定义更改为* Connection
Change the handler definition to be of type *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)
}
https://play.golang.org/p/8H2FocX5U9
这篇关于正确地传递结构以在golang中起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!