Where do the square brackets come from?

package main import ( "fmt" "log" ) func main() { a := []string{"abc", "edf"} log.Println(fmt.Sprint(a)) } 

In the above Go program, the following result will be printed, with the 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 [] added to the formatted string.

I checked the source code of src/fmt/print.go , but could not find the exact line of code that does this.

Can anyone give a hint?

+5
source share
1 answer

You print the slice value. It is formatted / printed in print.go , the outstanding 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 } 

Please note that this is for β€œcommon” fragments (for example, your []string ), byte sections are processed 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 unexcited 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 } 
+8
source

All Articles