-1

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?

Michel
  • 303
  • 2
  • 15
  • I think that a slice of interfaces cannot match an slice of other types, even if the type match the interface. Take a look at this long post: https://groups.google.com/forum/#!topic/golang-nuts/Il-tO1xtAyE – siritinga Jan 03 '15 at 16:25

2 Answers2

0

Your problem is that you're trying to use a value of type []models.Users{} as a value of type []Identifiable. While models.Users implements Identifiable, Go's type system is designed so that slices of values implementing an interface cannot be used as (or converted to) slices of the interface type.

See the Go specification's section on conversions for more details.

joshlf
  • 21,822
  • 11
  • 69
  • 96
0

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.

Michel
  • 303
  • 2
  • 15