I have golang error while putting struct into slice
完整代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package main import ( "net" ) var arrayOfConnections []*Connection type Connection struct { conn net.Conn id int } func main() { serv, _ := net.Listen("tcp",":8080") defer serv.Close() connectionHandle(serv) } func connectionHandle(serv net.Listener) { conn, _ := serv.Accept() arrayOfConnections = append(&Connection{conn, 1}, 0) conn.Write([]byte("one")) conn.Close() } |
有错误:
first argument to append must be slice; have *Connection
这部分代码中的错误:
arrayOfConnections = append(&Connection{conn, 1}, 0)
我是Golang的新手,很难弄清楚我在做什么错。如何重写代码,以便新连接最终可以附加到切片中?在stackoverflow上找不到答案。希望有人能帮忙。谢谢。
附件应该是这样的
1 | arrayOfConnections = append(arrayOfConnections, &Connection{conn, 1}) |
append内置函数跟随签名
1 | func append(s []T, vs ...T) []T |
当s是要添加的切片而vs是要添加到s的元素时,然后de function返回一个新的切片,其中添加了所有元素。