方括号从何而来?
Where do the square brackets come from?
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
文件,但找不到执行此操作的确切代码行。
有人可以提供提示吗?
您正在打印切片的值。它在 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 }
请注意,这是针对 "general" 个切片(就像您的 []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 }
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
文件,但找不到执行此操作的确切代码行。
有人可以提供提示吗?
您正在打印切片的值。它在 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 }
请注意,这是针对 "general" 个切片(就像您的 []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 }