Issue
I am learning go interfaces and trying to implement the below but vscode is showing me a compilation error, requesting help. What am I missing. Thank you.
package dataaccess
import (
"../domain"
)
type IProductDataAccess interface {
GetProducts() ([]*domain.Product, error)
GetProduct(string) (*domain.Product, error)
}
var (
ProductDataAccess IProductDataAccess
)
type productDAO struct{}
func init() {
ProductDataAccess = new(productDAO)
}
func (p *productDAO) GetProduct(productID string) (*domain.Product, error) {
return nil, nil
}
func (p *productDAO) GetProducts() ([]*domain.Product, error) {
return nil, nil
}
Getting the following compilation errors in the editor when making the method calls on the IProductDataAccess from a component as shown below in a different package
not enough arguments in call to dataaccess.IProductDataAccess.GetProduct
have (string)
want (dataaccess.IProductDataAccess, string) (WrongArgCount)
not enough arguments in call to dataaccess.IProductDataAccess.GetProducts
have ()
want (dataaccess.IProductDataAccess)compiler (WrongArgCount)
package service
import (
"../dataaccess"
"../domain"
)
type IProductService interface {
GetProducts() ([]*domain.Product, error)
GetProduct(string) (*domain.Product, error)
}
var (
ProductService IProductService
)
type productService struct{}
func init() {
ProductService = new(productService)
}
func (p *productService) GetProduct(productID string) (*domain.Product, error) {
product, err := dataaccess.IProductDataAccess.GetProduct(productID)
if err != nil {
return nil, err
}
return product, nil
}
func (p *productService) GetProducts() ([]*domain.Product, error) {
products, err := dataaccess.IProductDataAccess.GetProducts()
if err != nil {
return nil, err
}
return products, nil
}
Solution
This line looks like it needs adjustment:
product, err := dataaccess.IProductDataAccess.GetProduct(productID)
dataaccess.IProductDataAccess
is an interface, not an actual object to invoke a call on. dataaccess.ProductDataAccess
is the singleton instance on that page that what you want to invoke.
I think you really want:
product, err := dataaccess.ProductDataAccess.GetProduct(productID)
Similarly for the GetProducts call:
products, err := dataaccess.ProductDataAccess.GetProducts()
Answered By – selbie
Answer Checked By – Robin (GoLangFix Admin)