
本文将介绍如何使用 Go 语言的 Stringer 接口,自定义结构体的字符串格式化输出,避免使用反射,提高代码可读性和性能。通过实现 String() 方法,我们可以控制结构体成员的展示方式,例如将 byte 数组格式化为 "[0,0,0]",将 Char 数组格式化为 "ABCD"。
Go 语言提供了 fmt 包,用于格式化输出。默认情况下,使用 fmt.Printf("%#v\n", myStruct) 可以输出结构体的详细信息,但这种方式不够灵活,无法自定义输出格式。为了更优雅地格式化结构体,可以使用 Stringer 接口。
Stringer 接口定义如下:
type Stringer interface {
String() string
}如果一个类型实现了 String() 方法,那么 fmt 包在打印该类型的实例时,会自动调用 String() 方法,返回的字符串将被用于输出。
假设我们有以下结构体:
type Char byte
type CharSlice []Char
type ByteSlice []byte
func (s CharSlice) String() string {
ret := "\""
for _, b := range s {
ret += fmt.Sprintf("%c", b)
}
ret += "\""
return ret
}
func (s ByteSlice) String() string {
return fmt.Sprintf("%v", []byte(s))
}
type THeader struct {
Ver int8
Tag Char
}
func (t THeader) String() string {
return fmt.Sprintf("{ Ver: %d, Tag: %c}", t.Ver, t.Tag)
}
type TBody struct {
B1 [3]byte
B2 [4]Char
}
func (t TBody) String() string {
return fmt.Sprintf("{ B1: %s, B2: %s", ByteSlice(t.B1[:]), CharSlice(t.B2[:]))
}我们希望 THeader 和 TBody 结构体以特定的格式输出。为此,我们为这两个结构体实现了 String() 方法。
注意: 这里利用了类型别名 CharSlice 和 ByteSlice 分别实现了 String() 方法,从而避免了直接修改原始数组类型的行为。
package main
import (
"fmt"
)
type Char byte
type CharSlice []Char
type ByteSlice []byte
func (s CharSlice) String() string {
ret := "\""
for _, b := range s {
ret += fmt.Sprintf("%c", b)
}
ret += "\""
return ret
}
func (s ByteSlice) String() string {
return fmt.Sprintf("%v", []byte(s))
}
type THeader struct {
Ver int8 // will show 1
Tag Char // will show 'H'
}
func (t THeader) String() string {
return fmt.Sprintf("{ Ver: %d, Tag: %c}", t.Ver, t.Tag)
}
type TBody struct {
B1 [3]byte // will show "[0,0,0]"
B2 [4]Char // will show "ABCD"
}
func (t TBody) String() string {
return fmt.Sprintf("{ B1: %s, B2: %s", ByteSlice(t.B1[:]), CharSlice(t.B2[:]))
}
func main() {
th := THeader{1, 'H'}
fmt.Printf("%#v\n", th)
tb := TBody{B2: [4]Char{'A', 'B', 'C', 'D'}}
fmt.Printf("%#v\n", tb)
fmt.Printf("Txt(th):\n%s\n", th)
fmt.Printf("Txt(tb):\n%s\n", tb)
}运行结果如下:
main.THeader{Ver:1, Tag:72}
main.TBody{B1:[3]uint8{0, 0, 0}, B2:[4]main.Char{0x41, 0x42, 0x43, 0x44}}
Txt(th):
{ Ver: 1, Tag: H}
Txt(tb):
{ B1: [0 0 0], B2: "ABCD"可以看到,通过实现 Stringer 接口,我们成功地自定义了结构体的输出格式。
使用 Stringer 接口可以方便地自定义结构体的字符串格式化输出。与使用反射相比,这种方式更加高效且易于维护。在需要定制化输出结构体信息的场景下,Stringer 接口是一个非常实用的工具。
以上就是使用 Stringer 接口优雅地格式化 Go 结构体的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号