Print Byte Slice As String
ID |
go.print_byte_slice_as_string |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Go |
Tags |
CWE:1164, code-style, readability |
Description
Reports a []byte argument passed to a fmt print function (Print, Println, Sprint,
Sprintln, Fprint, Fprintln) without a string conversion.
Rationale
Without a conversion, those functions render a byte slice as its decimal byte values ([104 105])
rather than the text it holds. Wrapping it in string(b) prints the intended characters and reads
more clearly. The rule fires only for an unnamed []byte — either a []byte(…) conversion or a
so-typed identifier; named byte-slice types are left alone because they may implement fmt.Stringer,
in which case the print is already correct.
import "fmt"
func fn(b []byte) {
fmt.Print(b) // FLAW — prints byte values
fmt.Print(string(b)) // OK
}