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

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

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

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

使用示例

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 }

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

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

为接口注册一个构建函数

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

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

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

使用起来简单了很多。(不讨论性能问题,ddd 问题)


代码实现也比较简单,有兴趣的可以看下,https://github.com/attson/container