3

通过函数传递解决Go循环引用

 2 years ago
source link: https://helloteemo.github.io/2022/02/13/Golang/%E9%80%9A%E8%BF%87%E5%87%BD%E6%95%B0%E4%BC%A0%E9%80%92%E8%A7%A3%E5%86%B3Go%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

通过函数传递解决Go循环引用

发表于 2022-02-13 分类于 Golang 阅读次数: 28
本文字数: 869 阅读时长 ≈ 1 分钟

一个比较无耻的解决方案

这里讲的方法千万不要使用,为什么写这一篇文章是因为在工作中就很少想到有这样的奇淫巧技了。

我有一个a包,里面封装了用户的一些基本信息

// User basic user info
type User struct {
	Username string
	Password string
	IdCard   string
}

// UpdateUserInfo 更新用户信息
func UpdateUserInfo(idCard string) {
	b.UpdateUserInfo(getAgeFromIdCard(idCard))
}

func getAgeFromIdCard(idCard string) (age int) {
	// do something
	return
}

当用户更新信息的时候会调用 UpdateUserInfo 方法,但是用户的一些其余信息定义在了B包中。这里就产生了循环引用问题。

// User extend a.User
type User struct {
	a.User
	Age int `json:"age"`
}

// UpdateUserInfo 刷新用户信息
func UpdateUserInfo(age int) {
	// do something
}

我们可以保证A包是基本包,它始终不调用任意其余包,这样我们可以通过初始化的方式把B包中的方法传递给A包,这样就解决了循环引用问题,大概就是在A包中增加一个接口(广义的接口)使得A包可以通过调用本地方法的方式来调用B包中的函数。

// a包

var (
	BUpdateUserInfoFunc func(age int)
)

// b包
func Init() {
	a.BUpdateUserInfoFunc = UpdateUserInfo
}

当然也可以通过其余方式(比如消息队列或者其余的同步方法)

水了一周的文章,这样做的意义不大,甚至危害性极高,它使得基础包A包增加了过多的初始化依赖,并且有可能出现循环调用的问题,这无异于一场灾难。

请用钱砸死我!!!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK