英文:
Adding a method for existing type in Golang: how to rewrite return value's type
问题
我想要扩展现有的goquery.Selection类型,添加自己的方法,并且能够从包的选择器中使用它。我知道我不能“修补”现有的方法,我需要创建一个新的方法。但是,我如何强制现有的包函数使用我的新类型呢?我是否遗漏了一些通用的东西,或者没有“好”的方法来做到这一点,最好使用一个函数?
package main
import (
"fmt"
"github.com/PuerkitoBio/goquery"
)
type customSelection goquery.Selection
func (s *customSelection) CustomMethod() int {
return 1
}
doc.Find("*").Each(func(i int, s *goquery.Selection) {
fmt.Println(s.CustomMethod()) // 由于它仍然是"goquery.Selection",所以无法工作
// 我如何在这里获得customSelection类型的结果呢?
})
<details>
<summary>英文:</summary>
I want to extend existing [goquery.Selection][1] type with my own method and be able to use it from package's selectors. I know that I cannot "patch" existing method -- I need to create a new one. But how do I can force the existing package functions to use my new type? Something I'm missing in general or there's no "nice" way to do it and it's better to use a function?
package main
import (
"fmt"
"github.com/PuerkitoBio/goquery"
)
type customSelection goquery.Selection
func (s *customSelection) CustomMethod() int {
return 1
}
doc.Find("*").Each(func(i int, s *goquery.Selection) {
fmt.Println(s.CustomMethod()) // does not works since its still "goquery.Selection"
// how do I can get a result with customSelection type here?
})
[1]: http://godoc.org/github.com/PuerkitoBio/goquery#Selection
</details>
# 答案1
**得分**: 3
由于不支持继承,最佳实践是将非本地类型嵌入到自己的本地类型中,并进行扩展。
在设计模式中,这被称为组合:
https://en.wikipedia.org/wiki/Composition_over_inheritance
<details>
<summary>英文:</summary>
Since inheritance is not supported, the best practice is to embed the non-local type into your own local type, and extend it.
In the Design Patterns lingo its better known as composition:
https://en.wikipedia.org/wiki/Composition_over_inheritance
</details>
# 答案2
**得分**: 1
你可以使用函数代替方法:
```go
func customFunc(s *goquery.Selection) int {
return 1
}
...
fmt.Println(customFunc(s))
英文:
You can use function instead of method:
func customFunc(s *goquery.Selection) int {
return 1
}
...
fmt.Println(customFunc(s))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论