azani
azani

Reputation: 494

Passing objects that implement an interface with a pointer receiver

I understand that this has to do with the fact that Scale takes a pointer receiver. But I don't understand how I need to write PrintArea so this works.

package main

import (
        "fmt"
)

type Shape interface {
        Scale(num float64)
        Area() float64
}

type Square struct {
        edge float64
}

func (s *Square) Scale(num float64) {
        s.edge *= num
}

func (s Square) Area() float64 {
        return s.edge * s.edge
}

func PrintArea(s Shape) {
        fmt.Println(s.Area())
}

func main() {
        s := Square{10}
        PrintArea(s)
}

Here is the error I get as is.

# command-line-arguments
/tmp/sandbox126043885/main.go:30: cannot use s (type Square) as type Shape in argument to PrintArea:
    Square does not implement Shape (Scale method has pointer receiver)

Upvotes: 0

Views: 75

Answers (2)

dethtron5000
dethtron5000

Reputation: 10841

The Shape interface requires that the receiver has two methods - Scale and Area. Pointers to a type and the types themselves are considered different types in Go (so *Square and Square are different types).

To implement the interface, the Area and Scale functions must be on either the type or the pointer (or both if you want). So either

func (s *Square) Scale(num float64) {
    s.edge *= num
}

func (s *Square) Area() float64 {
    return s.edge * s.edge
}

func main() {
    s := Square{10}
    PrintArea(&s)
}

Upvotes: 2

Uvelichitel
Uvelichitel

Reputation: 8490

Just pass by reference

PrintArea(&s)

Upvotes: 0

Related Questions