5
votes

Attempting to create an interface, but methods have *Type, not Type receivers

APOLOGIZE: was sleepy and mis-read error messages. Thought I was being block from creating the DB interface when in reality I was mis-using it. Sorry about that... will be more careful in the future!

type Char string

func (*Char) toType(v *string) interface{} {
        if v == nil {
                return (*Char)(nil)
        }
        var s string = *v
        ch := Char(s[0])
        return &ch
}
func (v *Char) toRaw() *string {
        if v == nil {
                return (*string)(nil)
        }
        s := *((*string)(v))
        return &s
}

from here I would like an interface that contains the methods toType and toRaw

type DB interface{
        toRaw() *string
        toType(*string) interface{}
}

does not work since the function receivers are pointers. I say this because when I try to use it I get the error.k

    Char does not implement DB (toRaw method requires pointer receiver)

Is there a way to create an interface from toType and toRaw, or do I need to backup and have the receivers be the types themselves and not pointers to types?

2
Somehow it's difficult to get the idea behind your code. Please provide more infos.themue
trying to create DB interface using funcs toRaw and toType. but cannot since the receivers to the funcs are pointers. is there any way to declare a DB interface that incorporates toRaw and toType?cc young

2 Answers

4
votes

I don't understand what your problem is. Yes, the way you've written it, *Char conforms to the interface DB and Char doesn't. You can either

  1. change your code so that the methods operate on the non-pointer type Char directly (which will automatically also work for *Char too)
  2. only use *Char when you need something to be compatible with type DB
5
votes

If you define your interface methods for the pointer type you must pass a pointer to the methods/functions expecting the interface.