2016-06-28 117 views
5
package main 

import (
    "fmt" 
    "log" 
) 

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

上面的Go程序将打印下面的输出,切片值在方括号内"[]"方括号从哪里来?

2009/11/10 23:00:00 [ABC EDF]

而且我想知道在哪里的源代码[]加入到格式化字符串。

我检查了源代码src/fmt/print.go文件,但找不到确切的代码行。

任何人都可以提供提示吗?

回答

8

您正在打印切片的值。它被格式化/印刷print.go,未导出的函数printReflectValue(),目前线#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   } 

和线#995:

994   } else { 
995    p.buf.WriteByte(']') 
996   } 

请注意,这是为 “一般” 的切片(如您的[]string) ,字节切片不同的处理:

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被印刷在未导出函数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   } 
+0

非常感谢您的快速指出! – Bob