go泛型使用

51 阅读1分钟

前提条件:go版本大于1.18 #主体代码如下

package fanxing

import (
    "context"
    "fmt"
)

type DB interface {
    Config(ctx context.Context, file string)
    Open(ctx context.Context)
    Close(ctx context.Context)
}

type Conn[T DB] struct {
}

func (c *Conn[T]) Connect(ctx context.Context, db T, file string) {
    db.Config(ctx, file)
    db.Open(ctx)
    db.Close(ctx)
}

type DbConfig struct {
    config string
    file   string
    ctx    context.Context
}

func (d *DbConfig) Config(ctx context.Context, file string) {
    fmt.Println("load file:", file)
}

func (d *DbConfig) Open(ctx context.Context) {
    fmt.Println("open db")
}

func (d *DbConfig) Close(ctx context.Context) {
    fmt.Println("close file")
}

测试用例如下

package fanxing

import (
    "context"
    "testing"
)

func TestFanxing(t *testing.T) {
    conn := &Conn[*DbConfig]{}
    conn.Connect(context.Background(), &DbConfig{}, "config.yaml")
}

运行结果如下

=== RUN   TestFanxing
load file: config.yaml
open db
close file
--- PASS: TestFanxing (0.00s)
PASS

总结

使用起来也没啥难点,就是初写起来比较别扭,习惯了就好了,可以节省很多时间