基于 Golang 泛型实现的简单容器

Attson Lv3

概述

golang 1.18 有泛型之后,对业务代码的编写友好很多,可以更方便的实现一些不限类型的通用库。

最近尝试在 golang 中实现 ddd 的分层抽象,离不开注册和构建概念,如果没有泛型,那就需要很多强制业务代码中的类型转换代码,看起来不太优雅。

所以拿泛型实现了一个简单的容器,很方便解决了这个问题。

使用示例

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import "github.com/attson/container"

type Test struct {
Name string
}

func (t Test) Key() string {
return t.Name
}

type I interface {
Key() string
}

为结构体注册一个构建函数

1
2
3
4
5
6
7
8
9
// 为结构体注册一个构建函数
container.Register[Test](func() any {
return Test{
Name: "test",
}
})
// 通过容器构建实例
v1 := container.Make[Test]()
println(v1.Name) // test

为结构体指针注册一个构建函数

1
2
3
4
5
6
7
8
9
// 为结构体指针注册一个构建函数
container.Register[*Test](func() any {
return &Test{
Name: "test_pointer",
}
})
// 通过容器构建实例
v2 := container.Make[*Test]()
println(v2.Name) // test_pointer

为接口注册一个构建函数

1
2
3
4
5
6
7
8
9
// 为接口注册一个构建函数
container.Register[I](func() any {
return Test{
Name: "test_interface",
}
})
// 通过容器构建实例
v3 := container.Make[I]()
println(v3.Key()) // test_interface

在容器中设置一个实例(单例)

1
2
3
4
5
6
7
8
// 在容器中设置一个实例(单例)
container.Set[Test](Test{
Name: "test_set",
})
// 通过容器获取实例
v4 := container.Get[Test]()
println(v4.Name) // test_set

在容器中设置一个指针实例

1
2
3
4
5
6
7
// 在容器中设置一个指针实例
container.Set[*Test](&Test{
Name: "test_pointer_set",
})
// 通过容器获取实例
v5 := container.Get[*Test]()
println(v5.Name) // test_pointer_set

在容器中设置一个接口实例

1
2
3
4
5
6
7
// 在容器中设置一个接口实例
container.Set[I](Test{
Name: "test_interface_set",
})
// 通过容器获取实例
v6 := container.Get[I]()
println(v6.Key()) // test_interface_set

总结

总体使用起来简单了很多,这里针对比较复杂的业务项目,需要抽象实现分离等规范的项目

  • 标题: 基于 Golang 泛型实现的简单容器
  • 作者: Attson
  • 创建于 : 2023-10-19 00:00:46
  • 更新于 : 2023-10-18 16:13:23
  • 链接: https://attson.github.io/p/golang-container-base-genericity.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
 评论