该功能
fmt.Printf("%vn", data_interface)正是您想要的。它将打印传递给它的整个地图或数组。您可以在此处找到实现:http :
//golang.org/src/pkg/fmt/print.go?h=printArg#L708
printArg关键点附近的线是关键:
return p.printReflectValue(reflect.ValueOf(arg), verb, plus, goSyntax, depth
它使用“ reflect”包:http :
//golang.org/pkg/reflect/来查询参数的类型。内部内容
p.printReflectValue:http
:
//golang.org/src/pkg/fmt/print.go?h=printArg#L862您将看到两种处理地图和结构的情况。然后,它使用递归
printValue进行管理内容。
这是一段代码,它吸收结构的反射,然后将其转换回正确类型的另一个变量。您不能使用此方法从一种任意类型更改为另一种类型,必须在不使用反射的情况下将类型从一种强制转换为另一种是合法的。
package mainimport ( "fmt" "reflect")type Player stringtype Board struct { Tboard [9]string Player1 Player Player2 Player}// ignore this function contents, I grabbed it from elsewhere.func makeBoard() *Board { b := &Board{Tboard: [9]string{}} for x := 0; x < len(b.Tboard); x++ { b.Tboard[x] = "X" fmt.Println(b.Tboard[x]) } b.Player1 = "George" b.Player2 = "Tim" fmt.Printf("Len: %vn", len(b.Tboard)) // => 9 fmt.Printf("Contents: %vn", b) fmt.Printf("Syntax: %#vn", b) fmt.Printf("Type: %Tn", b) fmt.Println("Board:", b.Tboard) return b}func main() { myBoard := makeBoard() v := reflect.ValueOf(*myBoard) // v is of type Value t := v.Type() fmt.Printf("Value: %v %Tn", v, v) fmt.Printf("Type: %v %Tn", t, t) // would be a switch if t == reflect.TypeOf(*myBoard) { var b2 Board b2 = v.Interface().(Board) // cast the type interface{} into type Board fmt.Printf("v converted back to: %#vn", b2) } else { fmt.Printf("t is not recognized") }}请注意,类型
v为
main.Board,完整的软件包名称不是
Board。您要执行此操作的任何结构都必须具有导出类型,以使反射起作用。



