Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name of a struct to a string

Tags:

go

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)

like image 866
Jay Avatar asked Jan 09 '23 22:01

Jay


1 Answers

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.

like image 182
peterSO Avatar answered Feb 06 '23 17:02

peterSO