解决 "import circle " 错误的主要思路:
将循环import的部分的依赖于实现(struct)改为依赖于抽象(interface)
这里提供一种基于 handler
(即函数指针)的思路
下面的例子的总体package依赖关系:
复制代码
1
2
3
4main -----> auth , core auth ---> sdk core---> sdk
auth/ante.go
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package auth import ( "fmt" "youngqqcn/sdk" ) // 这里之所以用 dataFunc sdk.GetDataFunc 而不直接使用 core中的GetData函数 // 或者将GetData在此Dowork函数中实现, 是为了: // 1.解决 core/msgs_test.go "import circle"问题 // 2.根据设计原则, 降低模块间的耦合度, 不应该直接依赖实现, 而是依赖抽象(interface) func Dowork( msg sdk.Msg, dataFunc sdk.GetDataFunc ) { msg.DoSomething1() data, err := dataFunc(msg) if err != nil { fmt.Printf("error: %vn", err) } else { fmt.Println("ok==================%v", len(data)) } fmt.Println("Do work") }
core/msgs.go
复制代码
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
32package core import ( "fmt" "youngqqcn/sdk" ) type MsgSend struct { Data []byte } func NewMsgSend(data []byte) MsgSend { return MsgSend{ Data: data, } } func (msg MsgSend)DoSomething1() { fmt.Println("hello1") } func (msg MsgSend)DoSomething2() { fmt.Println("hello2") } func GetData(msg sdk.Msg) ([]byte, error) { if sendMsg, ok := msg.(MsgSend) ; ok{ return sendMsg.Data, nil } return []byte{}, nil }
core/msgs_test.go
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package core import ( "testing" "youngqqcn/auth" ) func TestMsgSend_DoSomething1(t *testing.T) { msg := NewMsgSend([]byte{}) auth.Dowork(msg, GetData) }
sdk/tx_msg.go
复制代码
1
2
3
4
5
6
7
8
9
10
11
12package sdk type Msg interface { DoSomething1() DoSomething2() } type GetDataFunc func(msg Msg) ([]byte, error)
main.go
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14package main import ( "fmt" "youngqqcn/auth" "youngqqcn/core"package main ) func main() { msg := core.NewMsgSend([]byte{0xff,0x55}) auth.Dowork(msg, core.GetData) fmt.Println("this is main function") }
最后
以上就是火星上心情最近收集整理的关于解决go中package依赖的一种思路--函数指针的全部内容,更多相关解决go中package依赖内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复