在使用该软件包完成工作后,请强制调用Close()函数。

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年3月1日 16:41:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/42526950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定