Interface conversion with bufio

I’m currently using go to do some course labs.I need a slice to store bufio.writer,here is what I do:

                   //slice to store bufio.writer
					var bufferQ []interface{}

					//bind file with buffer
					writer := bufio.NewWriter(file)
					bufferQ = append(bufferQ,writer)

But when I invoke it using following statements:bufferQ[0].WriteString(str), the compiler says something wrong:

# command-line-arguments
.\test.go:25:12: bufferQ[0].WriteString undefined (type interface {} is interface with no methods)
.\test.go:26:12: bufferQ[0].Flush undefined (type interface {} is interface with no methods)

Compilation finished with exit code 2

What should I do to get it right?

var bufferQ []*bufio.Writer

Your example:

package main

import (
	"bufio"
	"os"
)

func main() {
	//slice to store bufio.writer
	var bufferQ []*bufio.Writer

	var file *os.File

	//bind file with buffer
	writer := bufio.NewWriter(file)
	bufferQ = append(bufferQ, writer)

	var str string

	if len(bufferQ) > 0 {
		buffer := bufferQ[0]
		_, err := buffer.WriteString(str)
		if err != nil {
			// handle error
		}
		err = buffer.Flush()
		if err != nil {
			// handle error
		}
	}
}
2 Likes

Wow,this is more detailed than I thought,thanks very much!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.