gpt4 book ai didi

initialization - 用 Go 中的类型声明替换包装结构

转载 作者:IT王子 更新时间:2023-10-29 01:25:42 27 4
gpt4 key购买 nike

我想从 Go 标准库扩展 regexp 以便能够定义我自己的方法。我使用以下结构:

type RichRegexp struct {
*regexp.Regexp
}

如您所见,此结构仅包含包装的 regexp.Regexp。所以我想知道我是否可以用像这样的简单类型声明来替换它:

type RichRegexp regexp.Regexp

但是下面的func应该怎么写呢?

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?
}

我试图将 regexp.Regexp 转换为我的 RichRegexp 但它没有编译。返回包装基础类型的自定义类型的一般模式是什么?

最佳答案

您可以使用转换,但在这种情况下,您的类型定义必须不是指针:

type MyRegexp *regexp.Regexp // Doesn't work

这是由 the spec 支持的:

The receiver type must be of the form T or *T where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method. The method is said to be bound to the base type and the method name is visible only within selectors for that type.

但是,您可以这样做:

type MyRegexp regexp.Regexp

在处理值时,您可以执行以下操作:

x := regexp.MustCompile(".*")
y := MyRegexp(*x)

并且您有自己的正则表达式类型。

完整代码:http://play.golang.org/p/OWNdA2FinN

作为一般模式,我会说:

  • 如果它不太可能改变并且您不需要存储任意值,请使用类型转换。
  • 如果您需要将值与嵌入式类型一起存储,请使用struct
  • 如果您的代码可能会发生变化并且需要支持各种各样的东西,定义接口(interface)并且不使用嵌入/类型转换。

关于initialization - 用 Go 中的类型声明替换包装结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13219132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com