golang继承
golang继承
避免空指针
避免结构体 B 在使用 A 创建的连接时出现空指针错误。
初始化检查
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
type A struct {
MySQL *sql.DB
InfluxDB *influxdb.Client
OpenSearch *opensearch.Client
}
func (a *A) Init() error {
// 初始化 MySQL
var err error
a.MySQL, err = sql.Open("mysql", "user:password@/dbname")
if err != nil {
return err
}
// 初始化 InfluxDB
a.InfluxDB, err = influxdb.NewClient(influxdb.Options{
Addr: "http://localhost:8086",
})
if err != nil {
return err
}
// 初始化 OpenSearch
a.OpenSearch, err = opensearch.NewClient(opensearch.Config{
Addresses: []string{"http://localhost:9200"},
})
if err != nil {
return err
}
return nil
}
type B struct {
A *A
}
func (b *B) UseConnections() {
if b.A.MySQL == nil || b.A.InfluxDB == nil || b.A.OpenSearch == nil {
log.Fatal("Connections are not initialized")
}
// 使用 MySQL, InfluxDB, OpenSearch
}
依赖注入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
type A struct {
MySQL *sql.DB
InfluxDB *influxdb.Client
OpenSearch *opensearch.Client
}
func (a *A) Init() error {
// 初始化 MySQL
var err error
a.MySQL, err = sql.Open("mysql", "user:password@/dbname")
if err != nil {
return err
}
// 初始化 InfluxDB
a.InfluxDB, err = influxdb.NewClient(influxdb.Options{
Addr: "http://localhost:8086",
})
if err != nil {
return err
}
// 初始化 OpenSearch
a.OpenSearch, err = opensearch.NewClient(opensearch.Config{
Addresses: []string{"http://localhost:9200"},
})
if err != nil {
return err
}
return nil
}
type B struct {
MySQL *sql.DB
InfluxDB *influxdb.Client
OpenSearch *opensearch.Client
}
func NewB(a *A) *B {
return &B{
MySQL: a.MySQL,
InfluxDB: a.InfluxDB,
OpenSearch: a.OpenSearch,
}
}
func (b *B) UseConnections() {
// 使用 MySQL, InfluxDB, OpenSearch
}
懒加载
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
type A struct {
MySQL *sql.DB
InfluxDB *influxdb.Client
OpenSearch *opensearch.Client
}
func (a *A) Init() error {
// 初始化 MySQL
var err error
a.MySQL, err = sql.Open("mysql", "user:password@/dbname")
if err != nil {
return err
}
// 初始化 InfluxDB
a.InfluxDB, err = influxdb.NewClient(influxdb.Options{
Addr: "http://localhost:8086",
})
if err != nil {
return err
}
// 初始化 OpenSearch
a.OpenSearch, err = opensearch.NewClient(opensearch.Config{
Addresses: []string{"http://localhost:9200"},
})
if err != nil {
return err
}
return nil
}
type B struct {
A *A
}
func (b *B) UseConnections() error {
if b.A.MySQL == nil || b.A.InfluxDB == nil || b.A.OpenSearch == nil {
err := b.A.Init()
if err != nil {
return err
}
}
// 使用 MySQL, InfluxDB, OpenSearch
return nil
}
This post is licensed under CC BY 4.0 by the author.