草庐IT

go - 试图将文字转换为 Golang 中的指针

coder 2024-07-11 原文

为了简化我负责测试的代码的测试,我正在重构我团队的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 上使用这些函数。为了解决这个问题,我引入了一个结构 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

为什么不,我该怎么办?

最佳答案

" as Logger was an instance whereas the methods were on a *Logger".

停在那里。 Logger 是一个接口(interface)。方法“不在接口(interface)上”。具体的实现有一个具体的接收者类型,它将是*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 的指针。

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

关于go - 试图将文字转换为 Golang 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51898395/

有关go - 试图将文字转换为 Golang 中的指针的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  5. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  6. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  7. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  8. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  9. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  10. ruby - 如何使用文字标量样式在 YAML 中转储字符串? - 2

    我有一大串格式化数据(例如JSON),我想使用Psychinruby​​同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解

随机推荐