golang fmt格式化字符串%v,%T

前端之家收集整理的这篇文章主要介绍了golang fmt格式化字符串%v,%T前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

T常用的格式化字符串有:

%v the value in a default format
when printing structs,the plus flag (%+v) adds field names
%#v a Go-Syntax representation of the value
%T a Go-Syntax representation of the type of the value

不同类型默认的%v 如下:

bool: %t
int,int8 etc.: %d
uint,uint8 etc.: %d,%#x if printed with %#v
float32,complex64,etc: %g
string: %s
chan: %p
pointer: %p

对于interface{},%v会打印实际类型的值。
举例说明如下。

example

  1. package main
  2.  
  3. import (
  4.  
  5. "fmt"
  6. )
  7.  
  8.  
  9. type Power struct{
  10. age int
  11. high int
  12. name string
  13. }
  14.  
  15. func main() {
  16.  
  17. var i Power = Power{age: 10,high: 178,name: "NewMan"}
  18.  
  19. fmt.Printf("type:%T\n",i)
  20. fmt.Printf("value:%v\n",i)
  21. fmt.Printf("value+:%+v\n",i)
  22. fmt.Printf("value#:%#v\n",i)
  23.  
  24.  
  25. fmt.Println("========interface========")
  26. var interf interface{} = i
  27. fmt.Printf("%v\n",interf)
  28. fmt.Println(interf)
  29. }

output:

type:main.Power value:{10 178 NewMan} value+:{age:10 high:178 name:NewMan} value#:main.Power{age:10,high:178,name:”NewMan”} ========interface======== {10 178 NewMan} {10 178 NewMan}

猜你在找的Go相关文章