英文:
Correctly pass struct to function in golang
问题
我有一个Go语言的结构体:
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) {}
无法将newConnection
(类型为*Connection)作为参数传递给handler
。
谢谢。
英文:
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
得分: 5
问题是Handler
的类型是Connection
,而你传递的值的类型是*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)
}
https://play.golang.org/p/8H2FocX5U9
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论