英文:
Golang io.Pipe vs node.js Pipe
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我对Go语言还不熟悉,我在理解Go的io.Pipe
时遇到了问题。这个和Node.js的.pipe
类似吗?我应该如何使用它?能否将其用于一个读取文件和一个写入文件的操作?
提前感谢大家。
英文:
I'm new to golang and I'm having problem understanding go's io.Pipe
. Is this similar to node.js' .pipe
? And how should I use it? Is it possible to use it with 1 read file and a write file?
Thank in advance guys.
答案1
得分: 5
不,它们并不完全相似。io.Copy(dat io.Writer, src io.Reader)
足以用于读取和写入文件,就像这样:
input := bufio.NewReader(os.Stdin)
output := bufio.NewWriter(os.Stdout) // 像C标准库一样缓冲输出
io.Copy(output, input) // 复制整个文件
output.Flush()
io.Pipe() (*PipeReader, *PipeWriter)
会在你需要它们的代码中生成管道的Reader
和Writer
,就像这样:
type id struct{
name string
age int
}
payload := id{"John", 25}
requestBody, jsonPayload := io.Pipe()
request := http.NewRequest("POST", "http://www.example.com", requestBody) // NewRequest期望io.Reader
encoder := json.NewEncoder(jsonPayload) // NewEncoder期望io.Writer
err := encoder.Encode(payload)
response, err := client.Do(request)
英文:
No, they are not precisely similar. io.Copy(dat io.Writer, src io.Reader)
is quite enough to read and write files, like this:
input := bufio.NewReader(os.Stdin)
output := bufio.NewWriter(os.Stdout) // buffer output like C stdlib
io.Copy(output, input) // copy entire file
output.Flush()
io.Pipe() (*PipeReader, *PipeWriter)
will produce piped Reader
and Writer
for you when you have not them but code expect them, like this:
type id struct{
name string
age int
}
payload := id{"John", 25}
requestBody, jsonPayload := io.Pipe()
request := http.NewRequest("POST". "http://www.example.com", requestBody) // NewRequest expect io.Reader
encoder := json.NewEncoder(jsonPayload) // NewEncoder expect io.Writer
err := encoder.Encode(payload)
response, err := client.Do(request)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论