Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a method be defined both for a struct and its pointer?

Tags:

go

Given the setup in the 54th slide of the golang tour:

type Abser interface {
    Abs() float64
}

type Vertex struct {
    X, Y float64
}

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

Why can't a method also be defined for the struct as well as the pointer to the struct? That is:

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

Defining this gives the following error:

prog.go:41: method redeclared: Vertex.Abs
    method(*Vertex) func() float64
    method(Vertex) func() float64
like image 793
HaskellElephant Avatar asked Nov 10 '12 21:11

HaskellElephant


1 Answers

It can. Just define it on the struct and not the pointer. It will resolve both ways

Method Sets

The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T)

Try live: http://play.golang.org/p/PsNUerVyqp

package main

import (
    "fmt"
    "math"
    )

type Abser interface {
    Abs() float64
}

type Vertex struct {
    X, Y float64
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
    v := Vertex{5, 10}
    v_ptr := &v
    fmt.Println(v.Abs())
    fmt.Println(v_ptr.Abs())
}

Update: As per comments I have created an extra example that actually makes use of the Abser interface to illustrate that both the value and the pointer satisfy the interface.

https://play.golang.org/p/Mls0d7_l4_t

like image 87
jdi Avatar answered Nov 15 '22 15:11

jdi