dea*_*mon 5 initialization type-conversion go
我想扩展regexp
Go标准库,以便能够定义我自己的方法.我使用以下结构:
type RichRegexp struct {
*regexp.Regexp
}
Run Code Online (Sandbox Code Playgroud)
如您所见,此结构只包含包装regexp.Regexp
.所以我想知道我是否可以用这样的简单类型声明替换它:
type RichRegexp regexp.Regexp
Run Code Online (Sandbox Code Playgroud)
但是我该怎么写下面的函数呢?
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?
}
Run Code Online (Sandbox Code Playgroud)
我试图转换regexp.Regexp
为我,RichRegexp
但它没有编译.返回包装基础类型的自定义类型的一般模式是什么?
您可以使用转换,但在这种情况下,您的类型定义不是指针是必要的:
type MyRegexp *regexp.Regexp // Doesn't work
Run Code Online (Sandbox Code Playgroud)
这是由规范支持:
接收器类型必须是T或*T形式,其中T是类型名称.由T表示的类型称为接收器基类型; 它不能是指针或接口类型,必须在与方法相同的包中声明.据说该方法绑定到基类型,并且方法名称仅在该类型的选择器中可见.
但是,您可以这样做:
type MyRegexp regexp.Regexp
Run Code Online (Sandbox Code Playgroud)
在您现在处理值时,您可以执行以下操作:
x := regexp.MustCompile(".*")
y := MyRegexp(*x)
Run Code Online (Sandbox Code Playgroud)
你有自己的正则表达式类型.
完整代码:http://play.golang.org/p/OWNdA2FinN
作为一般模式,我会说:
struct
.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")
}
Run Code Online (Sandbox Code Playgroud)
另外在这里: http: //play.golang.org/p/cgpi8z2CfF
归档时间: |
|
查看次数: |
518 次 |
最近记录: |