如何在Golang中设置继承

tl;dr

What is the right way to set Store to be shared between multiple services in this example: https://github.com/th0th/goblog/blob/2b2d7ac51978de41f392396309424043817a49d7/store/store.go#L29

Details

Greetings, I am trying to comprehend how go works by creating a simple MVC-ish blog REST API. I have planned the application to consist of 3 packages/layers:

models

Holds the structs of data. Defines the interfaces for database access layers of these structs.

store

Presents the actual database connections. Implements the interfaces from models. All database access is done through this implementation.

api

REST API related stuff. Routes and such.

I have a Store struct in store package, which holds the services:

// Store wraps all services
type Store struct {
    DB *sqlx.DB

    CategoryService CategoryService
    PostService PostService
}

And here is the CategoryService (PostService is also like this. They both have methods for CRUD actions.):

// CategoryService represents a service for managing categories.
type CategoryService struct {
    store *Store
}

When I create an instance of this Store, I need to set store of every single service.

// New creates and returns new Store
func New() Store {
    var s Store

    db, err := sqlx.Connect("mysql", "<user>:<pass>@(localhost:3306)/goblog")

    if err != nil {
        log.Fatal(err)
    }

    s.DB = db

    s.CategoryService.store = &s
    s.PostService.store = &s

    return s
}

I want store to be shared between services, what is the correct approach? Am I doing something wrong?

I find a bit strange in your design that the Store knows about the services and the services know about the Store...to me that double dependency does not look right, but that's probably subject to debate.

If I were you, I would remove the services from the Store and pass the Store as parameter when you create the each service.

For example, remove the services from the store:

type Store struct {
  DB *sqlx.DB
  // no services here
}

...and pass the Store as a parameter when you create the service:

type CategoryService struct {
  store *Store
}

func NewCategoryService(s Store) CategoryService {
  var service CategoryService
  service.store = s
  return service
}

func (service CategoryService) Add()  {
  // service will have access to the store value
  // via service.store
}