Go: io: add StringWriter interface type

Created on 30 Sep 2018  路  2Comments  路  Source: golang/go

I propose that we export this interface:

// stringWriter is the interface that wraps the WriteString method.
type stringWriter interface {
        WriteString(s string) (n int, err error)
}

Strictly speaking, this is not necessary. One can declare it elsewhere, or use it inline such as w.(interface{ WriteString(string) (int, error) }).

However, I still think we should export it for a number of reasons:

  • Consistency. We export Writer and ByteWriter already, so I've expected io.StringWriter to exist many times in the past.
  • Better documentation. For example, If w implements a WriteString method in the godoc can be a bit confusing if one is not used to that interface and signature. If w implements StringWriter is much clearer.
  • Deduplication. In the standard library alone, the interface is copy-pasted at least five times, and I've seen it countless times elsewhere:
$ git grep 'type.*string.*interface {$'
fmt/fmt_test.go:type stringWriter interface {
io/io.go:type stringWriter interface {
net/http/h2_bundle.go:type http2stringWriter interface {
net/http/serve_test.go:         type stringWriter interface {
runtime/error.go:type stringer interface {
strings/replace.go:type stringWriterIface interface {

None of these points is a dealbreaker, but they do make learning and dealing with writers clunkier than it should be.

@dvyukov suggested exporting the interface in #21718, along with adding a WriteByte function. Note, however, that the issue was closed because it was decided that the function wasn't necessary. I agree with the decision. However, the interface should be considered separately.

FrozenDueToAge NeedsFix Proposal Proposal-Accepted help wanted

Most helpful comment

OK.

All 2 comments

OK.

Change https://golang.org/cl/139457 mentions this issue: io: export StringWriter

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ashb picture ashb  路  3Comments

gopherbot picture gopherbot  路  3Comments

longzhizhi picture longzhizhi  路  3Comments

OneOfOne picture OneOfOne  路  3Comments

enoodle picture enoodle  路  3Comments