dongluo3962 2012-11-04 13:53
浏览 29
已采纳

在Go中用类型声明替换包装结构

I want to extend the regexp from the Go standard library to be able to define my own methods. I use the following struct:

type RichRegexp struct {
    *regexp.Regexp
}

As you can see, this struct contains nothing but the wrapped regexp.Regexp. So I wonder whether I could replace this with a simple type declaration like this:

type RichRegexp regexp.Regexp

But how should I write the following func then?

func Compile(expression string) (*RichRegexp, error) {
    regex, err := regexp.Compile(expression)
    if err != nil {
        return nil, err
    }
    return &RichRegexp{regex}, nil // How to do this?
}

I tried to convert regexp.Regexp to my RichRegexp but it didn't compile. What is the general pattern to return a custom type which wraps a underlying type?

  • 写回答

2条回答 默认 最新

  • 红酒泡绿茶 2012-11-04 14:11
    关注
    package main
    
    import (
            "regexp"
    )
    
    type RichRegexp regexp.Regexp
    
    func Compile(expression string) (*RichRegexp, error) {
            regex, err := regexp.Compile(expression)
            if err != nil {
                    return nil, err
            }
    
            return (*RichRegexp)(regex), nil
    }
    
    func main() {
        Compile("foo")
    }
    

    Also here: http://play.golang.org/p/cgpi8z2CfF

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计