实现一个返回指针的函数。

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

Implement a function which returns a pointer

问题

我已经在我的golang应用程序中实现了syslog守护进程服务。我在主包中使用了syslog.New,并且它可以正常工作,但是现在,我想将它导出到另一个包中。

package config

import (
	"log/syslog"
)

func LogBook() ? {
	sysLog, _ := syslog.New(syslog.LOG_LOCAL0|syslog.LOG_ERROR, "myapp") // syslog.New返回(*Writer, error)
	return ?
}

我该如何实现这个函数?
然后,我该如何在其他包中使用这个变量'sysLog'?

谢谢!

英文:

I have implemented the syslog daemon service in my golang app. I used syslog.New in main package and it works but now, I want to export it to another package.

package config

import (
	"log/syslog"
)

func LogBook() ? {
	sysLog, _ := syslog.New(syslog.LOG_LOCAL0|syslog.LOG_ERROR, "myapp") // syslog.New returns (*Writer, error)
	return ?
}

How can I implement this function?
After, how can I use this variable 'sysLog' in other packages?

Thank you!

答案1

得分: 2

答案很简单,就像@Volker所说的那样,

func LogBook() *syslog.Writer {
    sysLog, _ := syslog.New(syslog.LOG_LOCAL0|syslog.LOG_ERROR, "myapp")
    return sysLog
}

用法示例:

func main(){
    w := LogBook()
    w.Info("message")
}

请注意:

  • 此包在Windows上未实现。由于syslog包已经冻结,建议Windows用户使用标准库之外的包。有关背景,请参阅https://golang.org/issue/1108。
  • 此包在Plan 9上未实现。
  • 此包在NaCl(Native Client)上未实现。
英文:

The answer is pretty simple as @Volker said,

func LogBook() *syslog.Writer {
    sysLog, _ := syslog.New(syslog.LOG_LOCAL0|syslog.LOG_ERROR, "myapp")
    return sysLog
}

Usage Example:

func main(){
    w := LogBook()
    w.Info("message")
}

Please notice:

  • This package is not implemented on Windows. As the syslog package is frozen, Windows users are encouraged to use a package outside of the standard library. For background, see https://golang.org/issue/1108.
  • This package is not implemented on Plan 9.
  • This package is not implemented on NaCl (Native Client).

huangapple
  • 本文由 发表于 2017年5月9日 17:20:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/43865923.html
匿名

发表评论

匿名网友

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

确定