package main
import (
"fmt"
"log"
)
func main() {
a := []string{"abc", "edf"}
log.Println(fmt.Sprint(a))
}
The above Go program will print the following output, with slice value inside the square brackets "[]"
.
2009/11/10 23:00:00 [abc edf]
And I want to know where in the source code that []
is added into the formatted string.
I checked the source code src/fmt/print.go
file, but couldn't find the exact line of code that does this.
Could anyone provide a hint?
You are printing the value of a slice. It is formatted / printed in print.go
, unexported function printReflectValue()
, currently line #980:
855 func (p *pp) printReflectValue(value reflect.Value, verb rune, depth int)
(wasString bool) {
// ...
947 case reflect.Array, reflect.Slice:
// ...
979 } else {
980 p.buf.WriteByte('[')
981 }
and line #995:
994 } else {
995 p.buf.WriteByte(']')
996 }
Note that this is for "general" slices (like your []string
), byte slices are handled differently:
948 // Byte slices are special:
949 // - Handle []byte (== []uint8) with fmtBytes.
950 // - Handle []T, where T is a named byte type, with fmtBytes only
[]byte
is printed in the unexported function fmtBytes()
:
533 func (p *pp) fmtBytes(v []byte, verb rune, typ reflect.Type, depth int) {
// ...
551 } else {
552 p.buf.WriteByte('[')
553 }
// ...
566 } else {
567 p.buf.WriteByte(']')
568 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With