1

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?

  • [Edit] your question with a [mcve] directly in the question as text; no external links. – Stephen Newell Aug 01 '23 at 04:46
  • 2
    Go does not allow declaring methods on types outside of the packages in which the types were declared. In other words, you cannot declare a method on `entities.Cat` inside the package `repositories`. You can only declare the method on `Cat` inside the package `entities`. – mkopriva Aug 01 '23 at 04:49

2 Answers2

2

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

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)
}
Mou Sam Dahal
  • 273
  • 2
  • 10