如何在结构体中使用io.Writer?

huangapple go评论132阅读模式
英文:

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 (
	&quot;io&quot;
	&quot;os&quot;
)

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 &lt; 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 &amp;Writer{writer: writer_thread, buferred_bytes: make([]byte, 0, buffer_size)}
}

func main() {

	w := NewWriter(os.Stdin, 4)
	w.Write([]byte(&quot;Hello world my friend&quot;))

}

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

huangapple
  • 本文由 发表于 2022年8月12日 02:19:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/73325247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定