1

I'm writing a package in go that creates a connection to Kafka.

I create the connection in the init() function in the main file in the package. After the program that uses the package stops, I want to call a function called Close()

Is there a way to enforce it in the package level, instead of giving this responsibility to the user?

Assume that the connection should be available throughout the run of the user's program, I don't want to initialize it every time.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Dotan
  • 6,602
  • 10
  • 34
  • 47
  • 1
    You can't enforce such a thing. You may take advantage of [`runtime.SetFinalizer()`](https://golang.org/pkg/runtime/#SetFinalizer), but it doesn't give you guarantees. See related question: [How to make sure that a method is used after an object is created in golang?](http://stackoverflow.com/questions/36826232/how-to-make-sure-that-a-method-is-used-after-an-object-is-created-in-golang/36826362#36826362) – icza Mar 01 '17 at 08:46
  • You should also avoid `SetFinalizer()`, especially in Go 1.8, because it can, in some situations, end up being called early. – Jonathan Hall Mar 01 '17 at 09:49
  • 6
    Document your package properly. Things like cleaning up are the responsibility of the user. The more a package _tries_ to take care of things behind the scenes, the more likely it is to cause problems for the users in the long run. – Elias Van Ootegem Mar 01 '17 at 10:04

1 Answers1

0

As for just about any resource (and a connection is no different), a user should call the functions to return resources to the system after use. Most users understand this across languages and architectures, so I don't see why your package users should have any concern. Go addresses this problem very elegantly by including the defer statement which makes it very easy to provide for releasing a resource.

Ravi R
  • 1,692
  • 11
  • 16