0

I have a go program, MyPackage, and a logging package within this, MyPackage/logs. We have a function func Cleanup(params CleanupParams) written in MyPackage that we want to use as a callback in case of any panic within our log function implemented in MyPackage/logs. This function is already written and being used by MyPackage, so we could all the code across but this would be very messy and involve a lot of copying dependent functions.

The approach I am thinking is this: In MyPackage, we have a function func SetupLogs, and could pass this Cleanup callback function as a parameter. However this ends up being a circular dependency, just since we have reference to a function on MyPackage from our logs package. Is there a way to pass this function, maybe with type any?

package MyPackage

import . "MyPackage/logs"

func main() {
   cleanupParams := ...

   ...

   SetupLogs(Cleanup, cleanupParams)

   ...
}

func Cleanup(params *CleanupParams) {
   ...
}

And our logs package:

package MyPackage/logs

type LogCallback func(*CleanupParams)

func SetupLogs(callback LogCallback, cleanupParams *CleanupParams) {
   ...

   go LogLoop(callback, cleanupParams)
}

func LogLoop(callback LogCallback, cleanupParams *CleanupParams) {
   defer callback(cleanupParams)
   
   for {
      // Keep checking if we have been channelled another message to log
      // If we are logging and have to Panic() then our callback gets run
   }
}

So is there any way to call the parent function from the imported class, since we don't need to know anything about the types of the function or its parameters, we just need to push our program to make sure the method gets called?

Thank you!

MattyAB
  • 365
  • 2
  • 9
  • 19
  • 2
    Passing a function (defined in`MyPackage`) to the `logs` package is not circular reference. Only if the `logs` package would import `MyPackage` explicitly. So I don't see a problem here. Please post "enough" code that reproduces the error, aim for a [mcve]. – icza Sep 07 '22 at 15:48
  • 1
    In case you're not aware, note that with the use of TitleCase for package names, and the use of dot-imports, you're violating two conventions of idiomatic Go. – mkopriva Sep 07 '22 at 18:35

0 Answers0