英文:
Enforce calling Close() when finished working with the package
问题
我正在使用Go语言编写一个创建与Kafka连接的包。
我在包的主文件的init()
函数中创建连接。在使用该包的程序停止后,我想调用一个名为Close()
的函数。
有没有一种方法可以在包级别上强制执行这个操作,而不是将这个责任交给用户?
假设连接应该在用户程序的整个运行过程中可用,我不想每次都初始化它。
英文:
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.
答案1
得分: 0
关于任何资源(包括连接),用户在使用后应调用函数将资源返回给系统。大多数用户跨语言和架构都理解这一点,所以我不认为你的包用户应该有任何担忧。Go语言通过包含defer语句来非常优雅地解决了这个问题,它使释放资源变得非常容易。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论