目录
介绍
gotable是Golang的开源第三方库,它的主要功能是将数据组成表格并在CLI中打印,效果如下:
+---------------+-------------+
| country | city |
+---------------+-------------+
| China | Beijing |
| Japan | Tokyo |
| North Korea | Pyongyang |
+---------------+-------------+
gotable可以根据字段的长度自动调整每列的宽度,并且自动地将字段按照对齐要求显示。表格可以动态的新增列和数据。本篇博客是gotable库的中文使用文档,并伴随gotable库不断更新。
获取gotable
在github中获取
下载源码
git clone
使用git clone:
git clone https://github.com/liushuochen/gotable.git
go mod
在gomod中: (关于version的获取,请参考go mod 私有项目版本号指定)
require github.com/liushuochen/gotable <version>
API
创建table
使用函数Create创建一个空table。Create函数允许接收一个可变长字符串参数,用来表示table的列(Column)。
func Create(columns ...string) (*table.Table, error)
使用示例
package main
import (
"fmt"
"github.com/liushuochen/gotable"
)
func main() {
_, err := gotable.Create("id", "name")
if err != nil {
fmt.Println("create table failed: ", err.Error())
return
}
}
当输入一个有重复内容的列时,创建table会失败。
package main
import (
"fmt"
"github.com/liushuochen/gotable"
)
func main() {
_, err := gotable.Create("id", "name", "id")
if err != nil {
fmt.Println("create table failed: ", err.Error())
// output: create table failed: value id has exit
return
}
}
当没有任何列输入时,创建table失败(返回一个详细的错误类型*exception.ColumnsLengthError)。
package main
import (
"fmt"
"github.com/liushuochen/gotable"
)
func main() {
_, err := gotable.Create()
if err != nil {
fmt.Println("Create table failed: ", err.Error())
// output: Create table failed: columns length must more than zero
return
}
}
从结构体中创建空table
使用gotable函数CreateByStruct从一个结构体中创建一个空table。
函数签名
func CreateByStruct(v interface{}) (*table.Table, error)
使用示例
首先定义一个结构体。使用结构体标签`gotable:"column_name"`来指定column名称。对于没有使用结构体标签的字段,column名称默认与字段名称相同。
type Student struct {
Id string `gotable:"id"`
Name string
}
当结构体中不包含任何字段时,CreateByStruct函数创建table失败(返回一个详细的错误类型*exception.ColumnsLengthError)。
package main
import (
"fmt"
"github.com/liushuochen/gotable"
)
type Student struct {
Id string `gotable:"id"`
Name string
}
func main() {
_, err := gotable.CreateByStruct(&Student{})
if err != nil {
fmt.Println("Create table failed: ", err.Error())
}
}
获取版本信息
func Version() string
使用gotable函数Version获取gotable的版本信息:
package main
import (
"fmt"
"github.com/liushuochen/gotable"
)
func main() {
version := gotable.Version()
fmt.Println(version)
// output: gotable 5.18.0
}
获取版本列表
func Versions() []string
使用gotable函数Ve