英文:
How use io.Writer in struct?
问题
为什么当我尝试使用Write()方法从Writer写入数据时,没有任何反应?
(我正在尝试自己实现基本的bufio方法)
package main
import (
"io"
"os"
)
type Writer struct {
writer io.Writer
buffered_bytes []byte
}
func (w *Writer) Flush() {
w.writer.Write(w.buffered_bytes)
w.buffered_bytes = w.buffered_bytes[:0]
}
func (w *Writer) Write(data []byte) {
for i := 0; i < len(data); i++ {
if len(w.buffered_bytes) == cap(w.buffered_bytes) {
w.Flush()
}
w.buffered_bytes = append(w.buffered_bytes, data[i])
}
}
func NewWriter(writer_thread io.Writer, buffer_size int) *Writer {
return &Writer{writer: writer_thread, buffered_bytes: make([]byte, 0, buffer_size)}
}
func main() {
w := NewWriter(os.Stdin, 4)
w.Write([]byte("Hello world my friend"))
}
我认为我应该使用指向io.Writer的指针,但我不确定。
英文:
Why when i try use Write() to writer from Writer nothing happens?
(I'm trying to implement the basic bufio methods myself)
package main
import (
"io"
"os"
)
type Writer struct {
writer io.Writer
buferred_bytes []byte
}
func (w *Writer) Flush() {
w.writer.Write(w.buferred_bytes)
w.buferred_bytes = w.buferred_bytes[:0]
}
func (w *Writer) Write(data []byte) {
for i := 0; i < len(data); i++ {
if len(w.buferred_bytes) == cap(w.buferred_bytes) {
w.Flush()
}
w.buferred_bytes = append(w.buferred_bytes, data[i])
}
}
func NewWriter(writer_thread io.Writer, buffer_size int) *Writer {
return &Writer{writer: writer_thread, buferred_bytes: make([]byte, 0, buffer_size)}
}
func main() {
w := NewWriter(os.Stdin, 4)
w.Write([]byte("Hello world my friend"))
}
I think i should use pointer to io.Writer, but im not sure
答案1
得分: 1
我发现了一个问题。我正在使用os.Stdin
而不是os.Stdout
。
英文:
I found a problem. Im using os.Stdin
instead os.Stdout
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论