将结构体的名称转换为字符串。

huangapple go评论59阅读模式
英文:

Name of a struct to a string

问题

如何打印结构体类型的名称,以便我可以在打印语句中使用,类似于:

type MyStruct struct { ... }

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

如果可能的话,这是否被认为是一个慢操作?(即反射)

英文:

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)

答案1

得分: 9

例如,

package main

import "fmt"

type MyStruct struct{}

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

输出:

main.MyStruct

fmt %T 打印动词可以给出值的Go语法表示的类型。

Go的fmt包使用reflect包进行运行时反射。

英文:

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.

huangapple
  • 本文由 发表于 2014年9月2日 12:44:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/25616016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定