golang打印指针切片/数组的值

gz-wod / 2023-07-28 / 原文

 

FmtSlice2String方法可以将指针切片的值打印处理
package main

import (
	"fmt"
	"reflect"
)

type Student struct {
	Name string `json:"name" cn:"名字"`
	Age  uint64 `json:"age" cn:"年龄"`
}

func main() {
	s := make([]*Student, 0)
	student1 := &Student{
		Name: "张三",
		Age:  18,
	}
	student2 := &Student{
		Name: "李四",
		Age:  20,
	}
	s = append(s, student1)
	s = append(s, student2)
	fmt.Printf("student1:%v\n", student1)  //student1:&{张三 18}
	fmt.Printf("student2:%+v\n", student2) //student2:&{Name:李四 Age:20}
	fmt.Printf("student:%+v\n", s)         //student:[0xc000092060 0xc000092078]
	fmt.Printf("student:%#v\n", s)         //student:[]*main.Student{(*main.Student)(0xc000092060), (*main.Student)(0xc000092 078)}
	fmt.Printf("student:%v\n", s)          //student:[0xc000092060 0xc000092078]
	fmt.Print(FmtSlice2String(s))          //Name:张三 Age:18 Name:李四 Age:20

}

func FmtSlice2String(x any) (res string) {
	val := reflect.ValueOf(x)
	if val.Kind() == reflect.Ptr {
		val = val.Elem()
	}
	switch val.Kind() {
	case reflect.Struct:
		typ := val.Type()
		//获取结构体里的名称
		for i := 0; i < typ.NumField(); i++ {
			field := typ.Field(i)
			res += field.Name + ":" + FmtSlice2String(val.Field(i).Interface()) + " "
		}
	case reflect.Slice, reflect.Array:
		for i := 0; i < val.Len(); i++ {
			res += FmtSlice2String(val.Index(i).Interface())
		}
	default:
		res += fmt.Sprint(x)
	}
	return
}

// 参考 https://www.bilibili.com/read/cv9164755/