bsr
bsr

Reputation: 58742

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.

Upvotes: 3

Views: 4460

Answers (2)

dschofie
dschofie

Reputation: 276

You'll want to embed A within a struct for B. You can't declare new types with pointers.

type A struct{ value int }

// Important diff here:
type B struct{
    *A
}

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

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

Upvotes: 3

icza
icza

Reputation: 418645

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.

Upvotes: 6

Related Questions