Why does fmt.Println inside a goroutine not print a line?

后端 未结 4 962
野趣味
野趣味 2020-11-28 07:10

I have the following code:

package main

import \"net\"
import \"fmt\"
import \"bufio\"

func main() {
    conn, _ := net.Dial(\"tcp\", \"irc.freenode.net:66         


        
4条回答
  •  佛祖请我去吃肉
    2020-11-28 07:38

    Write data to a channel ch at the end of goroutine and read data from ch out of goroutine can make the main function waiting for goroutine print message.

    Here is an example:

    package main
    
    import "net"
    import "fmt"
    import "bufio"
    
    func main() {
    conn, _ := net.Dial("tcp", "irc.freenode.net:6667")
    
    reader := bufio.NewReader(conn)
    ch := make(chan byte, 1)
    go func() {
        str, err := reader.ReadString('\n')
        if err != nil {
            // handle it
            fmt.Println(err)
        }
        fmt.Println(str)
        ch <- 1
      }()
      <-ch
    }
    

提交回复
热议问题