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

时间:2015-08-03 06:41:03

标签: go

我想用自己的方法扩展现有的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())  // does not works since its still "goquery.Selection"
  // how do I can get a result with customSelection type here? 
})

2 个答案:

答案 0 :(得分:3)

由于不支持继承,最佳做法是将非本地类型嵌入到您自己的本地类型中,并对其进行扩展。

在设计模式术语中,它更为人所知: https://en.wikipedia.org/wiki/Composition_over_inheritance

答案 1 :(得分:1)

您可以使用函数代替方法:

func customFunc(s *goquery.Selection) int {
    return 1
}

...

fmt.Println(customFunc(s))