0

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)

2 Answers 2

2

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

The 2nd example will not work, the original s.edge will stay the same after calling Scale.
@OneOfOne - right - the compile error goes away, but the application logic isn't correct. I'll update the answer.
0

Just pass by reference

PrintArea(&s)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.