Io Writestring Byte Slice
ID |
go.io_writestring_byte_slice |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Go |
Tags |
CWE:1164, code-smell, readability |
Rationale
io.WriteString exists to write a string without an intermediate byte-slice conversion. Converting a
byte slice to a string only to pass it to WriteString allocates a copy of the data and then writes
it byte-for-byte; calling w.Write(b) directly avoids the round-trip. The rule fires only when the
second argument is a string(…) conversion of an unnamed []byte; a named byte-slice type or an
unresolved value is left alone.
import "io"
func fn(w io.Writer, b []byte) {
io.WriteString(w, string(b)) // FLAW — use w.Write(b)
io.WriteString(w, "literal") // OK
}