仿 common-lang 包的 go 语言工具库

common-lang-in-go

https://github.com/sjsdfg/common-lang-in-go

Java 程序员编写的类似 common-lang 工具包
包名就是要用大驼峰,不想改成 go 规范的包名。自己写的任性

how to use

go get github.com/sjsdfg/common-lang-in-go

StringUtils

  • IsEmpty(str string) bool
  • IsNotEmpty(str string) bool
  • IsAllEmpty(list ...string) bool
  • IsAnyEmpty(list ...string) bool
  • IsAnyNoneEmpty(list ...string) bool
  • IsBlank(str string) bool
  • IsNotBlank(str string) bool
  • IsZero(str string) bool
  • IsNotZero(str string) bool
  • IsAnyZero(list ...string) bool
  • IsAllZero(list ...string) bool
  • IsAnyNoneZero(list ...string) bool
  • Equal(str1, str2 string) bool
  • EqualIgnoreCase(str1, str2 string) bool
  • EqualsAny(str string, list ...string) bool
  • EqualsAnyIgnoreCase(str string, list ...string) bool
  • IsDigital(str string) bool
  • DefaultIfEmpty(str, defaultStr string) string
  • If(condition bool, ifTrue, ifFalse string) string
  • Truncate(str string, startIndex, endIndex int) string

CollectionUtils

match functions

  • AllMatch(list interface{}, action matchFunc) bool
  • AnyMatch(list interface{}, action matchFunc) bool
  • NoneMatch(list interface{}, action matchFunc) bool

Use Case

func TestAllMatch(t *testing.T) {
    testCase := []string{"a", "a", "a"}
    assert.Equal(t, true, AllMatch(testCase, func(index int) bool {
        return testCase[index] == "a"
    }))

    testCase = []string{"a", "a", "b"}
    assert.Equal(t, false, AllMatch(testCase, func(index int) bool {
        return testCase[index] == "a"
    }))
}

func TestAnyMatch(t *testing.T) {
    testCase := []string{"a", "a", "b"}
    assert.Equal(t, true, AnyMatch(testCase, func(index int) bool {
        return testCase[index] == "b"
    }))

    testCase = []string{"a", "a", "b"}
    assert.Equal(t, false, AnyMatch(testCase, func(index int) bool {
        return testCase[index] == "c"
    }))
}

func TestNoneMatch(t *testing.T) {
    testCase := []string{"a", "a", "b"}
    assert.Equal(t, true, NoneMatch(testCase, func(index int) bool {
        return testCase[index] == "c"
    }))

    testCase = []string{"a", "a", "b"}
    assert.Equal(t, false, NoneMatch(testCase, func(index int) bool {
        return testCase[index] == "b"
    }))
}

empty judgement

  • IsEmpty(collection interface{})
  • IsNotEmpty(collection interface{}) bool

map function

这个是由于没有 Java Stream 里面的 map,导致每次提取某一类型的字段成为数组,写的代码十分冗余。所以抽象出来的。

由于不支持泛型,只能书写基本类型的方法调用。不过我的个人场景就是提取某一个字段(尤其是 id),目前还够用。

  • MapToStringSlice(list interface{}, action func(index int) string) []string
  • MapToIntSlice(list interface{}, action func(index int) int) []int
  • MapToInt64Slice(list interface{}, action func(index int) int64) []int64
  • MapToFloat64Slice(list interface{}, action func(index int) float64) []float64
  • MapToFloat32Slice(list interface{}, action func(index int) float32) []float32

Use Case

func TestMapToStringSlice(t *testing.T) {
    students := createStudents()
    timer := TimeUtils.NewTimer()
    reflectSlice := MapToStringSlice(students, func(i int) string {
        return students[i].name
    })
    t.Logf("MapToStringSlice cost %d nanos", timer.GetDurationInNanos())

    timer.Reset()
    nativeSlice := NativeMapToStringSlice(students)
    t.Logf("NativeMapToStringSlice cost %d nanos", timer.GetDurationInNanos())
    assert.Equal(t, nativeSlice, reflectSlice)
}

iterate

  • ForEach(list interface{}, action func(index int)):之前写 Java 写惯了,觉得使用 return 代替 continue 是可读性更高的代码,因为可以提早返回减少代码的嵌套接口。因此抽象出了该方法
func TestForEach(t *testing.T) {
    students := createStudents()
    ForEach(students, func(index int) {
        t.Log(students[index])
    })

    ForEach(students, func(index int) {
        students[index].name = "testing"
    })

    ForEach(students, func(index int) {
        assert.Equal(t, "testing", students[index].name)
    })
}

注意

以上方法类型为 FunctionName(list interface{}, action func(index int)) 均可以替换为 FunctionName(len int, action func(index int))

比如 ForEach 的实现可以为

func ForEach(len int, action func(i int)) {
    for i := 0; i < len; i++ {
        action(i)
    }
}

这个版本的运行效率更高。但是考虑到边界检查的安全性问题,我还是更倾向于传入 list 进来,通过反射来获取列表的长度。相关代码可查看 https://github.com/sjsdfg/common-lang-in-go/blob/faster/CollectionUtils/collection_utils.go

Float32Utils

  • Max(list ...float32) float32
  • Min(list ...float32) float32
  • If(condition bool, ifTrue, ifFalse float32) float32
  • Abs(a float32) float32
  • Equal(a, b float32) bool

Float64Utils

  • Max(list ...float64) float64
  • Min(list ...float64) float64
  • If(condition bool, ifTrue, ifFalse float64) float64
  • Abs(a float64) float64
  • Equal(a, b float64) bool

Int64Utils

  • Max(list ...int64) int64
  • Min(list ...int64) int64
  • If(condition bool, ifTrue, ifFalse int64) int64
  • Abs(a int64) int64

IntUtils

  • Max(list ...int) int
  • Min(list ...int) int
  • If(condition bool, ifTrue, ifFalse int64) int
  • Abs(a int) int

TimeUtils

  • Max(list ...time.Time) time.Time
  • Min(list ...time.Time) time.Time
  • If(condition bool, ifTrue, ifFalse int64) time.Time

上面的 XxxUtils 根据类型进行抽象,提供了最大值最小值的方法。并且因为 go 语言没有提供三目表达式,提供了 If 方法出来。可以边写出来可读性更高的代码

最佳实践

// 待实现
主要是想配合 IDEA 的 live template 和 Postfix completion 进行快捷键的搭配。

这样可以更好的使用该库。

Benchmark

CollectionUtils

CollectionUtils#IsEmpty

goos: darwin
goarch: amd64
pkg: github.com/sjsdfg/common-lang-in-go/CollectionUtils
BenchmarkIsEmpty                        22247214            54.3 ns/op
BenchmarkIsEmpty-2                      23466332            51.7 ns/op
BenchmarkIsEmpty-4                      23064122            51.4 ns/op
BenchmarkIsEmpty-8                      23634132            51.5 ns/op
BenchmarkNativeIsEmpty
BenchmarkNativeIsEmpty                  20717202            53.7 ns/op
BenchmarkNativeIsEmpty-2                23106975            50.9 ns/op
BenchmarkNativeIsEmpty-4                22869487            51.1 ns/op
BenchmarkNativeIsEmpty-8                23977856            51.1 ns/op
PASS

CollectionUtils#MapToStringSlice


BenchmarkMapToStringSlice
BenchmarkMapToStringSlice                4942840           292 ns/op
BenchmarkMapToStringSlice-2              4770552           263 ns/op
BenchmarkMapToStringSlice-4              4740819           302 ns/op
BenchmarkMapToStringSlice-8              5007906           238 ns/op
BenchmarkNativeMapToStringSlice
BenchmarkNativeMapToStringSlice         10728244           113 ns/op
BenchmarkNativeMapToStringSlice-2       10394302           113 ns/op
BenchmarkNativeMapToStringSlice-4       10965626           112 ns/op
BenchmarkNativeMapToStringSlice-8       10831770           113 ns/op
PASS
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270