duanlu0386 2017-10-13 18:41
浏览 38
已采纳

为什么我从io.PipeReader中获得EOF?

I’m using something similar in a project and I'm a bit perplexed: why isn't anything being printed?

package main
import (
    "fmt"
    "encoding/json"
    "io"
)

func main() {
    m := make(map[string]string)
    m["foo"] = "bar"

    pr, pw := io.Pipe()
    go func() { pw.CloseWithError(json.NewEncoder(pw).Encode(&m)) }()

    fmt.Fscan(pr)
}

https://play.golang.org/p/OJT1ZRAnut

Is this a race condition of some sort? I tried removing pw.CloseWithError but it changes nothing.

  • 写回答

1条回答 默认 最新

  • duanrong5927 2017-10-13 19:32
    关注

    fmt.Fscan takes two arguments. A reader to read from, and one or more pointers to objects to populate. Its result is (n int, err error), where n is the number of items read, and err is the reason why n is less than the (variadic...) slice of data objects you fed into its second argument.

    In this case, the slice of data objects is length zero, so Fscan fills zero objects and reads no data. It dutifully reports that it scanned 0 objects, and since that number is not less than the number of objects you passed into it, it reports nil error.

    Try the following:

    func main() {
        m := make(map[string]string)
        m["foo"] = "bar"
    
        pr, pw := io.Pipe()
        go func() { pw.CloseWithError(json.NewEncoder(pw).Encode(&m)) }()
    
        var s string
        n, err := fmt.Fscan(pr, &s)
        fmt.Println(n, err)  // should be 1 <nil>
        fmt.Println(s)       // should be {"foo":"bar"}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys