我在go代码中遇到了循环依赖关系的问题(不允许导入循环),并且不确定如何解决该问题的最佳方法。我认为我对golang接口的缺乏了解可能会影响我了解前进道路的能力。
我的问题-我有两个软件包:
允许Workout在事件域中调用函数(而不是对象上的方法)的最佳方法是什么?
下面是我的简化代码,以帮助提供一些上下文
//workout package
//This is a private function on the workout package that is
//attempting to call a public function on the Event Package
func findWorkoutAssociatedToActivityTcx(txcObject *DataTcx) *EventWorkout{
return event.GetEventByDate(txcObject.ActivityDate, "", "")
}
是否可以在该函数中创建接口?我不完全了解我该怎么做。非常感谢你。
//更新-尝试设置接口的代码
//WorkoutPackage
//workout package
//This is a private function on the workout package that is
//attempting to call a public function on the Event Package
func findWorkoutAssociatedToActivityTcx(txcObject *DataTcx, userID, transactionID string) *Workout {
//return event.GetEventByDate(txcObject.ActivityDate, "", "")
MyEventFinder.GetEventByDate(txcObject.ActivityDate, userID, transactionID)
return nil
}
var MyEventFinder EventFinder
type EventFinder interface {
GetEventByDate(time.Time, string, string) (*sharedstructs.ListOfEvents, error)
}
//事件包
type eventProvider struct{}
func (e eventProvider) GetEventByDate(date time.Time, userID, transactionID string) (*sharedstructs.ListOfEvents, error) {
redFalconLogger.LogDebug("event.GetEventByDate: ", transactionID)
if date.IsZero() || userID == "" {
return nil, sharedstructs.InvalidData{Msg: "Invalid date or userID"}
}
//Create the query params
queryParamArray, queryParamCreationError := createQueryParamForQueryByDate(&date, &userID)
if queryParamCreationError != nil {
return nil, queryParamCreationError
}
//perform the query - pass empty orderBy because I don't care
queryResults, queryError := queryForEvent(*queryParamArray, "")
if queryError != nil {
switch queryError.(type) {
case firestorehelper.UnqueryableCollection:
return nil, sharedstructs.Forbidden{Msg: "operation is forbidden, probably due to malformed query"}
default:
return nil, sharedstructs.InternalServerError{Msg: "something went wrong in the query"}
}
}
return queryResults, nil
}
最佳答案
您发现可以通过界面执行此操作。在事件包中,您需要为GetEventByDate提供一个接收器结构:
type eventProvider struct {}
func (e eventProvider) GetEventByDate(t time.Time, a, b string) *workout.EventWorkout{...}
然后在健身包中:
type EventFinder interface {
GetEventByDate(time.Time, string, string) *EventWorkout
}
然后,您可以将
eventProvider
实例传递到锻炼包中,并仅通过EventFinder
接口使用该实例,该接口对event
包没有编译时间依赖性。您没有显示如何调用workout
包,但这可以作为方法调用的参数,也可以在锻炼包中构造结构时进行设置。