Search code examples
interfacegomgo

Go compile error "undefined function"


I have the following pieces of code:

Interface & function definition:

package helper

import "gopkg.in/mgo.v2/bson"

// Defines an interface for identifiable objects
type Identifiable interface {
    GetIdentifier() bson.ObjectId
}

// Checks if a slice contains a given object with a given bson.ObjectId
func IsInSlice(id bson.ObjectId, objects []Identifiable) bool {
    for _, single := range objects {
        if single.GetIdentifier() == id {
            return true
        }
    }
    return false
}

The definition of the user struct which satisfies 'Identifiable':

package models

import (
    "github.com/my/project/services"
    "gopkg.in/mgo.v2/bson"
)

type User struct {
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    Username string          `json:"username" bson:"username"`
    Email    string          `json:"email" bson:"email"`
    Password string          `json:"password" bson:"password"`
    Albums   []bson.ObjectId `json:"albums,omitempty" bson:"albums,omitempty"`
    Friends  []bson.ObjectId `json:"friends,omitempty" bson:"friends,omitempty"`
}

func GetUserById(id string) (err error, user *User) {
    dbConnection, dbCollection := services.GetDbConnection("users")
    defer dbConnection.Close()
    err = dbCollection.Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&user)
    return err, user
}

func (u *User) GetIdentifier() bson.ObjectId {
    return u.Id
}

A test which checks for the existence of an object inside a slice:

package controllers

import ( 
    "github.com/my/project/helper"
    "gopkg.in/mgo.v2/bson"
)


var testerId = bson.NewObjectId()
var users = []models.Users{}

/* Some code to get users from db */

if !helper.IsInSlice(testerId, users) {
    t.Fatalf("User is not saved in the database")
}

When I try to compile the test it I get the error: undefined helper.IsInSlice. When I rewrite the IsInSlice method to not take []Identifiable but []models.User it works fine.

Any ideas?


Solution

  • Apparently, Go did not rebuild my package and was looking for the function in an old build. It was therefore undefined. Performing rm -fr [GO-ROOT]/pkg/github.com/my/project/models did the trick.