-1

I have an interface TagService with a struct implementation. They reside in two different packages due to SoC. I want to instantiate the implementation, and add it to a another struct Handler, which has a field of the interface type.

This takes place in the main package:

package main

...

ts := &postgres.TagService{DB: db} 
var h http.Handler
h.TagService = ts

However, with this setup, i receive the following error in VS code:

cannot use ts (variable of type *postgres.TagService) as *tagservice.TagService value in assignment

The Handler struct:

type Handler struct {
    TagService *tagservice.TagService
}

The interface:

package tagservice

type Tag struct {
    ID          int64
    Name        string
    Description string
}

type TagService interface {
    CreateTag(tag *Tag) (*Tag, error)
    GetTag(id int64) (*Tag, error)
    GetAllTags() ([]*Tag, error)
    UpdateTag(tag *Tag) (*Tag, error)
    DeleteTag(id int64) error
}

And the implementation (Omitted func bodies)

package postgres

type TagService struct {
    DB *sql.DB
}

func (s *TagService) CreateTag(tag *tagservice.Tag) (*tagservice.Tag, error) {
...
}

func (s *TagService) GetTag(id int64) (*tagservice.Tag, error) {
...
}

func (s *TagService) GetAllTags() ([]*tagservice.Tag, error) {
...
}

func (s *TagService) UpdateTag(tag *tagservice.Tag) (*tagservice.Tag, error) {
...
}

func (s *TagService) DeleteTag(id int64) error {
...
}

What am I doing wrong? Thanks in advance

Mike Hawkins
  • 2,144
  • 5
  • 24
  • 42
  • 1
    Because you are trying to put pointer to the interface instead of just interface. Try ```type Handler struct { TagService tagservice.TagService }``` – Oleksii Miroshnyk Mar 28 '20 at 22:48
  • Fix by declaring the field as `TagService tagservice.TagService`. See [Why can't I assign a *Struct to an *Interface?](https://stackoverflow.com/questions/13511203/why-cant-i-assign-a-struct-to-an-interface) for an explanation. – Charlie Tumahai Mar 28 '20 at 22:48
  • Change the `Handler` to use a `tagservice.TagService` instead of `*tagservice.TagService`. That's a pointer to an interface. – Burak Serdar Mar 28 '20 at 22:48
  • Thank you all. Works perfectly. – Mike Hawkins Mar 28 '20 at 23:10
  • 1
    @OleksiiMiroshnyk, can you convert your comment into an answer so it can be accepted? – Cameron Little Apr 02 '20 at 06:05

1 Answers1

2

You are trying to put pointer to the interface instead of just interface. Try

type Handler struct { 
    TagService tagservice.TagService 
}