在Golang中为现有类型添加方法:如何重写返回值的类型

huangapple go评论68阅读模式
英文:

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&#39;s selectors. I know that I cannot &quot;patch&quot; 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&#39;m missing in general or there&#39;s no &quot;nice&quot; way to do it and it&#39;s better to use a function?

    package main
    
    import (
    	&quot;fmt&quot;
    	&quot;github.com/PuerkitoBio/goquery&quot;
    )
    
    type customSelection goquery.Selection
    
    func (s *customSelection) CustomMethod() int {
    	return 1
    }
    
    doc.Find(&quot;*&quot;).Each(func(i int, s *goquery.Selection) {
      fmt.Println(s.CustomMethod())  // does not works since its still &quot;goquery.Selection&quot;
      // 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)) 

huangapple
  • 本文由 发表于 2015年8月3日 14:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/31780876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定