Adding a method for existing type in Golang: how to rewrite return value's type

I want to extend existing goquery.Selection 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? 
})

Answers


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


You can use function instead of method:

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

...

fmt.Println(customFunc(s)) 

Need Your Help

Batch move files to directory with csv

file batch-file csv directory move

I have a folder with files that i need to be moved over to the directory listed in the csv file. All the files are in one folder but they need to go to different directories.

HS Canvas image hover/swap

javascript jquery html css canvas

The idea of the project is to make a widget from this image, I know it's in B&W grey scale full. I have each image with the text in a separate image for example First green section of each of the