How to implement interface in golang?

251 views Asked by At

I have 3 files in a project in Go:

Cat.go

package entities

type Cat struct {
    Length              int
    Origin              string
    Image_link          string
    Family_friendly     int
    Shedding            int
    General_health      int
    Playfulness         int
    Children_friendly   int
    Grooming            int
    Intelligence        int
    Other_pets_friendly int
    Min_weight          int
    Max_weight          int
    Min_life_expectancy int
    Max_life_expectancy int
    Name                string
}

cat.repository.go

package src

import entities "src/domain/entitites"

type CatRepository interface {
    ListCats() []entities.Cat
}

cat.repository.impl.go

package repositories

import (
    entities "src/domain/entitites"
    nir "src/domain/repositories"
)


func (cat entities.Cat) ListCats() []entities.Cat {

}

I am trying to implement interface on third file but compiler says "cannot define new methods on non-local type entitites.Cat"

Someone could tell me how to solve it?

2

There are 2 answers

0
Victor Vieira On

Looks like you're trying to add methods to your struct Cat in a different package. If your intent is to reuse the Cat structure as a repository for the same entity, you should add the methods in the Cat.go file.

If you want to isolate the repository from cat structure, you should probably declare a new struct called CatRepositoryImpl and add a methods to that struct. Additionally, you can put that struct into the cat.repository folder.

0
Mou Sam Dahal On

For what you asked, you can create a seperate repo and then implement methods using that repo like below,

package repositories
...

type repo struct {
 cat entities.Cat
}

func (r *repo) ListCats() []entities.Cat {
  // now you can access cat using
  print(r.cat)
}