DEV Community

晓道
晓道

Posted on

3 3

go printf小技巧

go语言里面,三种打印结构体的方式,原来没有注意,今天觉得%v看起来感觉不好,认真看了下文档,写一篇记录一下。

1,%v 仅打印结构体的值
2,%+v 打印结构体的字段名+字段值
3,%#v 在2的基础上加了结构体名

上代码:

package main

import "fmt"

type employee struct {
    name   string
    age    int
    salary int
}

func main() {
    emp := employee{name: "Sam", age: 31, salary: 2000}
    fmt.Printf("%v\n", emp)
    fmt.Printf("%+v\n", emp)
    fmt.Printf("%#v\n", emp)
    //{Sam 31 2000}
    //{name:Sam age:31 salary:2000}                 
    //main.employee{name:"Sam", age:31, salary:2000}
}
Enter fullscreen mode Exit fullscreen mode

再给大家推荐一个字符串格式化的库,
lwahlmeier/pyfmt: Golang implementation of PEP3101 (github.com)
主要我写习惯了python的格式化方式,在go里,没有python这种f字符串挺难受,这个库就可以实现f字符串的功能。
使用方法,直接代码吧:

import (
    "fmt"
    py "github.com/lwahlmeier/pyfmt"
)
type employee struct {
    name   string
    age    int
    salary int
}
func main() {
    emp := employee{name: "Sam", age: 31, salary: 2000}
    fmt.Println(py.Must("{:s}", emp))
    fmt.Println(py.Must("{:r}{0:t}", emp))
    fmt.Println(py.Must("{0.name} {0.age}", emp))
    //{name:Sam age:31 salary:2000}
    //main.employee{name:"Sam", age:31, salary:2000}main.employee
    //Sam 31
}
Enter fullscreen mode Exit fullscreen mode

1,{:s} 打印结构体,字段和值
2, {:r} 打印结构体名,{:t}打印类的类型
3, {0.name} 0表示一个,.后接的字段名
后面这个库,更详细的看文档吧,前面有github地址。

参考文章
Pretty print struct variables in Go (Golang) - Welcome To Golang By Example

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up