duan2477 2018-09-05 22:18
浏览 61
已采纳

在Golang中使用接收器返回函数

I am new to Golang. And I am trying to use a decorator which returns a function with a receiver. How can I do that?

type myStruct struct {
    s string
}

func myFunc(s string) {
    fmt.Println(s)
}

// Here I want to return a function with a receiver
func (*myStruct) myDecorator(fn func(string)) (*myStruct)func(string){
    return (ms *myStruct)func(s string) {
        fn(ms+s)
    }
}

func main() {
    ms := myStruct{"Hello"}
    // Some func is function with receiver as myStruct pointer
    someFunc := myDecorator(myFunc)
    // This is expected to print "Hello world"
    ms.someFunc(" world")
}
  • 写回答

1条回答 默认 最新

  • dptn69182 2018-09-05 23:52
    关注

    As noted in my comment, you cannot modify the method set of a type in the return from a function call, so directly extending the behavior of the myStruct struct is not possible in your "decorator" function as written.

    I am actually using this decorator to wrap fmt.Sprintf, Sprintln, Sprint method to get Logger.Debugln, Logger.Debugf, Logger.Warning, ... methods, where Logger is a self-defined struct, since these functions shares almost the same behavior.

    You also will not be able to pass around the fmt.Sprintf, fmt.Sprintln and fmt.Sprint functions in a generic way, as they share different signatures:

    func Print(a ...interface{}) (n int, err error)
    func Printf(format string, a ...interface{}) (n int, err error)
    func Println(a ...interface{}) (n int, err error)
    

    so you will need to wrap these methods separately.

    It isn't entirely clear to me how you are seeking to wrap those methods to produce your Logger type.

    If you require each of those methods at the top level of your logger, they will need to be explicitly declared in your logging package or on your Logger type's interface. You cannot dynamically bind each level function at runtime, despite their obvious similarities; go is a statically-typed language so your types must be declared upfront.

    Defining the types explicitly will be the clearest solution, which is also in keeping with a key go proverb: "Clear is better than clever."

    If necessary, you can declare each method as a simple wrapper of an internal method on your type which actually performs the printing logic, keeping repetition to a minimum.

    Here's a quick example I threw together to show the logic for some Debug, Debugf and Debugln endpoints. You can see the core logic is handled by a generic set of methods on the Logger type, and you can imagine how endpoints for other log levels could be trivially implemented.

    If repetition is really a problem, you could trivially write a code generator to automatically generate the log-level specific methods, calling on the core functionality explicitly declared in the various print functions. Remember you can declare receivers for a type in multiple source files in the same package, allowing some methods to be generated in some source files while others are implemented explicitly elsewhere.

    package main
    
    import (
        "fmt"
        "io"
        "os"
    )
    
    type Level string
    
    const (
        Debug Level = "DEBUG"
        Error       = "ERROR"
    
    // etc.
    )
    
    type Logger struct {
        writer       io.Writer
        prependLevel bool
    }
    
    func (l *Logger) print(level Level, msg string) {
        var s string
        if l.prependLevel {
            s = string(level) + ": "
        }
        s += msg
        fmt.Fprint(l.writer, s)
    }
    
    func (l *Logger) printf(level Level, format string, a ...interface{}) {
        l.print(level, fmt.Sprintf(format, a...))
    }
    
    func (l *Logger) println(level Level, msg string) {
        l.printf(level, "%s
    ", msg)
    }
    
    func (l *Logger) Debug(msg string) {
        l.print(Debug, msg)
    }
    
    func (l *Logger) Debugf(format string, a ...interface{}) {
        l.printf(Debug, format, a...)
    }
    
    func (l *Logger) Debugln(msg string) {
        l.println(Debug, msg)
    }
    
    func main() {
        logger := Logger{os.Stderr, true}
        logger.Debugln("A plain message with a new line")
        logger.Debugf(
            ("The most customizable log entry with some parameters: " +
                "%s %v
    "),
            "myStr", false,
        )
        logger.Debug("A bare print statement")
    }
    

    Playground link.


    Third-party packages

    In case you haven't yet done so, there are many third-party logging packages in Go which I would recommend considering, or at least assessing their interfaces to determine how others have approached similar tasks.

    Logrus is a Go logger with levels, for example. You can see in their source files how they explicitly declare their interface for each function at each log level, while using a more comprehensive version of the method above to reduce repetition in the core logging implementation: Interface Formatter implementations

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图