Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

io: add WriteByte/StringWriter for symmetry #21718

Closed
dvyukov opened this issue Aug 31, 2017 · 3 comments
Closed

io: add WriteByte/StringWriter for symmetry #21718

dvyukov opened this issue Aug 31, 2017 · 3 comments

Comments

@dvyukov
Copy link
Member

dvyukov commented Aug 31, 2017

io provides WriteString function and ByteWriter interface. Is there any reason for this asymmetry? I think it should also provide WriteByte function and StringWriter interface. Or, at least, WriteByte function, which is a handy short-cut and avoids byte slice allocation:

func WriteByte(w Writer, b byte) (n int, err error) {
  	if bw, ok := w.(io.ByteWriter); ok {
  		return bw.WriteByte(b)
  	}
  	return w.Write([]byte{b})
}
@cespare cespare changed the title io: add WriteByte/StringWriter assymetry io: add WriteByte/StringWriter for symmetry Aug 31, 2017
@ianlancetaylor ianlancetaylor added this to the Unplanned milestone Aug 31, 2017
@ianlancetaylor
Copy link
Contributor

Does it really come up all that often without using an explicit bufio.NewWriter?

@dvyukov
Copy link
Member Author

dvyukov commented Sep 1, 2017

I guess I need to use bufio.NewWriter more. Sorry for the noise.

@dvyukov dvyukov closed this as completed Sep 1, 2017
@bibainet
Copy link

bibainet commented Sep 1, 2017

There is stringWriter interface already in the io package, but it is not exported. It would be useful in some cases. For example: Currently, the net/http.ResponseWriter interface is implemented by *net/http.response, which is also implements io.stringWriter (http.response already has WriteString method). But there is no WriteString in net/http.ResponseWriter interface. So, you should call io.WriteString(w, s) instead of w.WriteString(s) every time when you need to write the small data chunk into w. It would be better to cast http.ResponseWriter to io.stringWriter only once instead of doing this every time you call io.WriteString (but specifically in this case it would be better to add WriteString into http.ResponseWriter).

@golang golang locked and limited conversation to collaborators Sep 1, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants