go – Multiple "classes" with same function names

Exception or error:

I’m trying to extract some data from myanimelist and imdb using Go.
The searches is expected to be quite different depending on site that data is collected from therefor a different function (with same name) is needed for myanimelist and imdb. Currently I try to sum my functions in a struct and call upon them through the struct. However this isnt working as expected.

type myAnimeList interface {
    search(url string, name string) (string, bool)
    getScore(url string, regex string) (string, bool)
    getTop(url string, regex string) (string, bool)
    getEpisodes(url string, regex string) (string, bool)
    getInfo(url string, regex string) (string, bool)
    getAired(url string, regex string) (string, bool)
}

My plan is eventually to use a dictionary like:

var SitesAvailable = map[string]interface{}{
    "myanimelist":  http.MyAnimeList,
    "myanimelist2": http.MyAnimeList,
}

Were I can decide which search method I want active and call upon them.
It may look something like:

SitesAvailable["myanimelist"].search(url, seriesName)

I am quite confused in my thinking and dont have a clear structure on how I can do this. But what I want is a dictionary where I can decide which search method that should be used and some way to separate the imdb functions from myanimelist functions. There must be in the same package.

Any guidance on how I can accomplish this?

Update 1

So I followed @syazdani example with an common interface and I now have the following. It seem to work as I wanted and improved the structure a bit.

type Website interface {
    Search() (string, bool)
    GetScore()
    GetTop() (string, bool)
    GetInfo()
    GetAired()
}

type myAnimeList struct {
    score    string
    rank     string
    episodes string
    info     string
    aired    string
    genre    string
    response string
    url      string
}

func (d myAnimeList) GetSeasonal() (string, bool){
//...
}
func (d myAnimeList) GetTop() (string, bool) {
//...
}
/*(repeat with all functions named in the Website interface)*/

var SitesAvailable = map[string]Website{
    "myanimelist":  http.MyAnimeList,
    "myanimelist2": http.MyAnimeList,
}

In order to access the functions call the following:

SitesAvailable["myanimelist"].Search(url, name)

Since Search takes two arguments of type string that has to be used too.

How to solve:

You should probably look into the Factory pattern to solve this issue. You define an interface (like you have with myAnimeList above, but probably with a more generic name), but then you also need to provide two separate implementations (one for IMDB and another for myAnimeList). I hope that helps!

See here for how to implement interfaces in golang.

Leave a Reply

Your email address will not be published. Required fields are marked *