Please explain me, why this happens


(Akezhan Esbolatov) #1

Hello, please explain me this , in the first example dogs method needs pointer so then i declare Dog in animal slice it works fine but when i declare it lite Dog{} compiler says

cannot use Dog literal (type Dog) as type Animal in array or slice literal:
Dog does not implement Animal (Speak method has pointer receiver)

but in the second example then i declare method of dog without pointer it works fine with pointer and without pointer (&Dog, Dog{}) both are correct

first:

package main

import (
	"fmt"
)

type Animal interface {
	Speak() string
}

type Dog struct {
}

func (d *Dog) Speak() string {
	return "BARK!"
}

func main() {
	animals := []Animal{&Dog, }
	for _, animal := range animals {
		fmt.Println(animal.Speak())
	}
}

second

    package main

import (
	"fmt"
)

type Animal interface {
	Speak() string
}

type Dog struct {
}

func (d Dog) Speak() string {
	return "BARK!"
}

func main() {
	animals := []Animal{Dog{}, }
	for _, animal := range animals {
		fmt.Println(animal.Speak())
	}
}

(Sunny Karira) #2

&Dog{} is what you are looking for.
&Dog{} would add a new animal in animal slice.


(Akezhan Esbolatov) #3

Actuallu i need explonation, why in the first example i can pass only pointer(&Dog{})
and in the second exmaple both are valid pointers and values (&Dog{}, Dog{})


(adriel) #4

@Akezhan_Esbolatov, In your first example, You try to pass a concrete type to an interface type, Dog itself does not implement the Animal interface, only a pointer to the Dog. In the second example (Dog.Speak()) satisfies method of the interface.


(Sunny Karira) #5

It is not always possible to get the address of a value.
Because it’s not always possible to get the address of a value, the method set for a value only includes methods that are implemented with a value receiver.

01 // Sample program to show how you can't always get the
02 // address of a value.
03 package main
04
05 import "fmt"
06
07 // duration is a type with a base type of int.
08 type duration int
09
10 // format pretty-prints the duration value.
11 func (d *duration) pretty() string {
12     return fmt.Sprintf("Duration: %d", *d)
13 }
14
15 // main is the entry point for the application.
16 func main() {
17     duration(42).pretty()
18
19     // ./listing46.go:17: cannot call pointer method on duration(42)
20     // ./listing46.go:17: cannot take the address of duration(42)
21 }
The code in listing 5.46 attempts to get the address of a value of type duration and can’t. This shows that it’s not always possible to get the address of a value. Let’s look at the method set rules again.

(system) #6

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.