Correctly pass struct to function in golang

huangapple go评论81阅读模式
英文:

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)

}

https://play.golang.org/p/8H2FocX5U9

huangapple
  • 本文由 发表于 2014年6月30日 00:03:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/24477790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定