Search code examples
gopointersmethods

invalid receiver for pointer (alias) type


It seems quite basics, but I couldn't easily correct the below program https://play.golang.org/p/8IJn7g0m1As


import (
    "fmt"
)

type A struct{ value int }
type B *A

func (b B) Print() {
    fmt.Printf("Value: %d\n", b.value)
}

func main() {
    a := &A{1}
    b := new(B(a))
    b.Print()

}
./prog.go:10:6: invalid receiver type B (B is a pointer type)
./prog.go:16:12: B(a) is not a type

For the first, I tried changing the receiver to func (b *B) , that didn't work. For the second, I tried like &B{a}, that didn't work either.

A is actually a complex struct with mutex in it (a struct generated by protobuf), so I need to keep it as a pointer, at the same time need to define additional methods on it, so defining a new type B.


Solution

  • This is clearly forbidden by the language spec. Spec: Method declarations:

    The receiver is specified via an extra parameter section preceding the method name. That parameter section must declare a single non-variadic parameter, the receiver. Its type must be a defined type T or a pointer to a defined type T. T is called the receiver base type. A receiver base type cannot be a pointer or interface type and it must be defined in the same package as the method.

    You can't declare a method with receiver type *T where T is already a pointer type, and you also cannot add methods for types defined in other packages. The type declaration and the method declaration must be in the same package.