登录
首页 >  Golang >  Go问答

将文字转为 Golang 中的引用

来源:stackoverflow

时间:2024-03-08 10:21:24 299浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《将文字转为 Golang 中的引用》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

为了简化我负责测试的代码的测试,我正在重构我团队的 loghandler

他们有这样的事情:

type loghandlerst struct {
    path        string
    filename    string
    projectname string
}

var (
    //instance the project instance of log handler.
    instance loghandlerst
    //onresponseerror a function that can be set to be called on response error.
    onresponseerror func(context interface{}, response *http.response)
    //includestack will include all lines with the strings below in the debug stack.
    includestack = []string{"apiserver_sdk", "ezdineserver_sdk"}
)

//createloghandler creates and assigns a log handler instance for use by the project.
func createloghandler(path string, filename string, projectname string) loghandlerst {
    instance = loghandlerst{path: path, filename: filename, projectname: projectname}.
        fmt.println("log files are in \"" + path + "\"")
    return instance
}

//log logs a message given the type of message and the message itself.
func (handler *loghandlerst) log(logtype string, errmsg string) {
    fmt.println(errmsg)
    logfile, err := os.openfile(handler.path+"/"+handler.filename+" "+time.now().format("2006-01-02")+".log", os.o_wronly|os.o_create|os.o_append, 0777)
    if err != nil {
        fmt.println(err)
    }
    defer logfile.close()
    if _, err = logfile.writestring(`
` + logtype + " " + time.now().format("2006-01-02 15:04:05.000") + `: ` + errmsg + "\n"); err != nil {
        fmt.println(err)
    }
    logfile.sync()
}

//getprojectnames gets the projects to use for the log handler instance. usually used for the debug stack.
func (handler *loghandlerst) getprojectnames() []string {
    var projectnames = []string{handler.projectname}
    projectnames = append(projectnames, includestack...)
    return projectnames
}

//logerror logs an error given information.
func (handler *loghandlerst) logerror(errmsg string) {
    handler.log("error", errmsg)
}

//logwarning logs a warning given information.
func (handler *loghandlerst) logwarning(errmsg string) {
    handler.log("warn", errmsg)
}

//loginfo logs some information.
func (handler *loghandlerst) loginfo(errmsg string) {
    handler.log("info", errmsg)
}

正在测试的代码库中的许多方法在 instance 上使用这些函数。为了解决这个问题,我引入了一个 struct logger

// logger provides a generic implementation of the required methods.
//  provided for testing purposes
type logger interface {
    logerror(errmessage string)
    logwarning(errmessage string)
    loginfo(errmessage string)
}

直觉,尤其是来自 java 的直觉,告诉我将 instance 的声明更改为 logger。当然,这没有任何作用,因为 logger 是一个实例,而方法位于 *logger 上。因此,我更改为 instance *logger 并重构 createloghandler 以处理我刚刚创建的编译时错误:

//createloghandler creates and assigns a log handler instance for use by the project.
func createloghandler(path string, filename string, projectname string) loghandlerst {
    instance = &loghandlerst{path: path, filename: filename, projectname: projectname}
        fmt.println("log files are in \"" + path + "\"")
    return instance
}

我被告知:

cannot use LogHandlerSt literal (type *LogHandlerSt) as type *Logger in assignment:
*Logger is pointer to interface, not interface

为什么不,对此我能做什么?


解决方案


“因为 logger 是一个实例,而方法位于 *logger 上”。

停在那里。 logger 是一个接口。方法“不在接口上”。具体实现具有具体的接收器类型,该类型将是 *loghandlerst,而不是 *logger,也不是 logger。另外,loghandlerst 不实现 logger,仅实现 *loghandlerst,因为方法是使用指针接收器定义的。

如果您引入了 logger,则可以这样使用它:

var Instance Logger

func CreateLogHandler(path string, fileName string, projectName string) Logger {
    Instance = &LogHandlerSt{
        path: path,
        fileName: fileName,
        projectName: projectName
    }
    fmt.Println("Log files are in \"" + path + "\"")
    return Instance
}

由于只有 *loghandlerst 实现了 logger,因此您必须分配一个指向 instance 的指针。

请注意,您应该很少(如果有的话)使用指向接口的指针(例如 *logger)。相反,指向具体类型的指针应该包装在接口值中。

以上就是《将文字转为 Golang 中的引用》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>