Confusing for these codes of interface implementation and calling.Someone please help.

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

  • go version go1.11 darwin/amd64

Does this issue reproduce with the latest release?

  • not testing

What operating system and processor architecture are you using (go env)?

  • not related

What did you do?

If possible, provide a recipe for reproducing the error.
A complete runnable program is good.
A link on play.golang.org is best.

Code 1:

package main

import "fmt"

type myintf interface {
	GotU()
}

type esc struct {
	 i int
}

//func GotU(t esc);
func (e esc)GotU() {
	e.i = 10
}

func TestFunc(it myintf) string {
	it.GotU()
	return  "kk"
}

func main() {

	var test esc
	test.i = 9

	TestFunc(test)

	fmt.Println(test.i)

}

Code 2:

package main

import "fmt"

type myintf interface {
	GotU()
}

type esc struct {
	 i int
}

func (e esc)GotU() {
	e.i = 10
}

func TestFunc(it myintf) string {
	it.GotU()
	return  "kk"
}

func main() {

	var test esc
	test.i = 9

	TestFunc(test)

	fmt.Println(test.i)

}

Code 3:

package main

import "fmt"

type myintf interface {
	GotU()
}

type esc struct {
	 i int
}

func (e *esc)GotU() {
	e.i = 10
}

func TestFunc(it myintf) string {
	it.GotU()
	return  "kk"
}

func main() {

	var test esc
	test.i = 9

	TestFunc(test)

	fmt.Println(test.i)

}

What did you expect to see?

  • nothing to expect

What did you see instead?

code 1 output: 9
code 2 output: 9
code 3 cannot be compiled due to a type mismatch

Since only func (e esc)GotU() implemented, why should both pieces of code work and deliver the same result?
It’s kind of confusing for me to pass a pointer of struct to that function (TestFunc) to get the same answer.

I believe the solution of your problem is send the struct as reference.
https://play.golang.org/p/Vucg9bflX9f

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