duanlu0386 2017-10-13 10: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 11: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"}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥100 二维码被拦截如何处理
  • ¥15 怎么解决LogIn.vue中多出来的div
  • ¥15 优博讯dt50巴枪怎么提取镜像
  • ¥30 在CodBlock上用c++语言运行
  • ¥15 求C6748 IIC EEPROM程序固化烧写算法
  • ¥50 关于#php#的问题,请各位专家解答!
  • ¥15 python 3.8.0版本,安装官方库ibm_db遇到问题,提示找不到ibm_db模块。如何解决?
  • ¥15 TMUXHS4412如何防止静电,
  • ¥30 Metashape软件中如何将建模后的图像中的植被与庄稼点云删除
  • ¥20 机械振动学课后习题求解答
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部