0

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

5
  • 1
    Because you are trying to put pointer to the interface instead of just interface. Try type Handler struct { TagService tagservice.TagService } Commented Mar 28, 2020 at 22:48
  • Fix by declaring the field as TagService tagservice.TagService. See Why can't I assign a *Struct to an *Interface? for an explanation. Commented Mar 28, 2020 at 22:48
  • Change the Handler to use a tagservice.TagService instead of *tagservice.TagService. That's a pointer to an interface. Commented Mar 28, 2020 at 22:48
  • Thank you all. Works perfectly. Commented Mar 28, 2020 at 23:10
  • 1
    @OleksiiMiroshnyk, can you convert your comment into an answer so it can be accepted? Commented Apr 2, 2020 at 6:05

1 Answer 1

3

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

type Handler struct { 
    TagService tagservice.TagService 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.