douhanxujiuji6098 2013-12-27 17:19
浏览 26
已采纳

Golang:您可以在接口中包装包装吗?

I'm writing a simple library to assist with common assertions.

type Test interface {
    Fatalf(string, ...interface{})
}

func IsTrue(statement bool, message string, test Test) {
    if !statement {
       test.Fatalf(message)
    }
}

I noticed that the log package actually has a compatible implementation of Fatalf(string, ...interface{}) and it'd be great if the IsTrue method could be invoked accordingly:

IsTrue(false, "false wasn't true", log)

But I get the error use of package log not in selector. Is there any way to use or wrap a package to make this pattern work or is this not possible?

  • 写回答

2条回答 默认 最新

  • donglv6960 2013-12-27 17:31
    关注

    The best you can hope for is to wrap it in a blank struct like so:

    type internalLog struct{}
    
    func (il internalLog) Fatalf(s string, i ...interface{}) {
        log.Fatalf(s, i...)
    }
    

    In general, since packages are not types in Go, they cannot satisfy anything. You have to wrap them in another type in order to simulate them satisfying an interface.

    Edit:

    As Caleb mentions (and I forgot about), the package log in specific has the function New which returns a *log.Logger which will satisfy the Test interface in your case (as well as most other package-level log functions). However, in general if no such type is provided you must wrap the package like I showed above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (标签-matlab)
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信