英文:
passing type with parameter in function call
问题
下面的代码来自Jan Newmarch关于Go网络编程的书籍。在我看到的大部分Go代码中(我是一个新手,所以看到的很少),在函数调用中不需要传递带有参数的类型。然而,在下面的代码中,你可以看到这一行:
conn.Write([]byte(daytime))
为什么在这个函数调用中需要包含[]byte?
func main() {
    service := ":1200"
    tcpAddr, err := net.ResolveTCPAddr("ip4", service)
    checkError(err)
    listener, err := net.ListenTCP("tcp", tcpAddr)
    checkError(err)
    for {
        conn, err := listener.Accept()
        if err != nil {
            continue
        }
        daytime := time.Now().String()
        conn.Write([]byte(daytime))
英文:
The code below is from Jan Newmarch's book about network programming in Go. In most of the Go code that I've seen (which is very little, as I'm a newbie, you don't (in a function call) pass a type with a parameter. However, in the code below, you see this line
conn.Write([]byte(daytime))
Why is it necessary to include []byte in this function call?
func main() {
	service := ":1200"
	tcpAddr, err := net.ResolveTCPAddr("ip4", service)
	checkError(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		daytime := time.Now().String()
		conn.Write([]byte(daytime))
答案1
得分: 3
Conn.Write() 期望的值是一个字节切片。由于 daytime 是字符串类型,所以你需要进行转换。
你可以将上述代码重写为:
daytime := []byte(time.Now().String())
conn.Write(daytime)
或者,如 @fabrizioM 所写,你可以使用格式化写入器进行转换:
fmt.Fprintf(conn, daytime)
英文:
Conn.Write() expects the value as a byte slice. Since daytime is of type string you have to convert it.
You could rewrite the above as:
daytime := []byte(time.Now().String())
conn.Write(daytime)
Or, as @fabrizioM writes, you could use the formatted writer which would convert it:
fmt.Fprintf(conn, daytime)
答案2
得分: 2
另一种方法是使用
fmt.Fprintf(conn, daytime)
英文:
Another way to do it is to use
fmt.Fprintf(conn, daytime)
答案3
得分: 0
因为在服务器和客户端之间传输的数据是字节(byte)。
在你的情况下,日期时间显然是字符串格式。
所以你需要使用[]byte(daytime)将其转换为字节。
另外,你可以导入"bufio"包为每个客户端创建一个NewWriter,并且NewWriter有WriteString("")方法。此时,你可以直接将你的日期时间作为参数传递进去。
英文:
Because the data being transferred between server and client is byte.
The daytime in your case is obviously string format.
So you have to convert it into byte by using []byte(daytime).
Either way, you could import "bufio" to create a NewWriter for each client, and the NewWriter
will have the methods WriteString(""). At this moment, you could directly pass your daytime
as a parameter~
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论