4

How do I print the name of the type of a struct, i.e. so I can include it in a print statement, i.e. something like

type MyStruct struct { ... }

func main() {
    fmt.Println(MyStruct.className())
}

If this is possible, would it be considered a slow operation? (i.e. reflection)

Jay
  • 19,649
  • 38
  • 121
  • 184

1 Answers1

9

For example,

package main

import "fmt"

type MyStruct struct{}

func main() {
    fmt.Printf("%T\n", MyStruct{})
}

Output:

main.MyStruct

The fmt %T print verb gives a Go-syntax representation of the type of the value.

The Go fmt package uses the reflect package for run-time reflection.

peterSO
  • 158,998
  • 31
  • 281
  • 276