I am writting something to tabwriter.Writer object,
w := tabwriter.NewWriter(os.Stdout, 5, 1, 3, ' ', 0)
fmt.Fprintf(w, "%v\t%v\t\n", somevalue1, somevalue2)
I can print the data in w in console using w.Flush() Is there any way so get values in w as string in one place and compare it with some value?
I want to compare what I have in w with some data.
You can implement your own io.Writer
:
type W []byte
func (w *W) Write(b []byte) (int, error) {
*w = append(*w, b...)
return len(b), nil
}
You can then pass an instance of *W
to tabwriter.NewWriter
:
sw := &W{}
w := tabwriter.NewWriter(sw, 5, 1, 3, ' ', 0)
fmt.Fprintf(w, "%v\t%v\t\n", somevalue1, somevalue2)
// get the string value from sw
str := string(*sw)
As sugested by @Tim, you should use *bytes.Buffer
instead for better performance and it already implements io.Writer
:
var b bytes.Buffer
w := tabwriter.NewWriter(&b, 0, 0, 1, '.', 0)
// ...
fmt.Println(b.String())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.