Interface Accepting Address of the Variable in Golang
The Print() methods accept a receiver pointer. Hence, the interface must also accept a receiver pointer.
If a method accepts a type value, then the interface must receive a type value; if a method has a pointer receiver, then the interface must receive the address of the variable of the respective type.
Example
package main
import "fmt"
type Book struct {
author, title string
}
type Magazine struct {
title string
issue int
}
func (b *Book) Assign(n, t string) {
b.author = n
b.title = t
}
func (b *Book) Print() {
fmt.Printf("Author: %s, Title: %s\n", b.author, b.title)
}
func (m *Magazine) Assign(t string, i int) {
m.title = t
m.issue = i
}
func (m *Magazine) Print() {
fmt.Printf("Title: %s, Issue: %d\n", m.title, m.issue)
}
type Printer interface {
Print()
}
func main() {
var b Book // Declare instance of Book
var m Magazine // Declare instance of Magazine
b.Assign("Jack Rabbit", "Book of Rabbits") // Assign values to b via method
m.Assign("Rabbit Weekly", 26) // Assign values to m via method
var i Printer // Declare variable of interface type
fmt.Println("Call interface")
i = &b // Method has pointer receiver, interface does not
i.Print() // Show book values via the interface
i = &m // Magazine also satisfies shower interface
i.Print() // Show magazine values via the interface
}
Most Helpful This Week
Implementing Multiple Interfaces in Go Programming Language
How to declare Interface Type in Go Programming Language
Polymorphism in Go Programming Language
Interface embedding another interface in Go Programming Language
Interfaces with similar methods in Go Programming Language
Defining a type that satisfies an interface in Go Programming Language
Type assertion in Go Programming Language
Empty Interface Type in Go Programming Language