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?
interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.
What is an interface in Go? An interface type in Go is kind of like a definition. It defines and describes the exact methods that some other type must have. We say that something satisfies this interface (or implements this interface) if it has a method with the exact signature String() string .
An interface in Go is a type defined using a set of method signatures. The interface defines the behavior for similar type of objects. An interface is declared using the type keyword, followed by the name of the interface and the keyword interface . Then, we specify a set of method signatures inside curly braces.
If you define your interface methods for the pointer type you must pass a pointer to the methods/functions expecting the interface.
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
Char
directly (which will automatically also work for *Char
too)*Char
when you need something to be compatible with type DB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With