Go函数传入结构体,而不是指针断言失败的问题

29 阅读1分钟
package main

import (
	"fmt"
	"reflect"
)

type MyInterface interface {
	GetName() string
}

type TestType1 struct{}

func (t TestType1) GetName() string { return "test1" }

type TestType2 struct{}

func (t *TestType2) GetName() string { return "test2" }

func GetTestName(m interface{}) {
	fmt.Printf("%v\n", reflect.TypeOf(m))
	if _, ok := m.(MyInterface); ok {
		fmt.Println("MyInterface")
	} else if _, ok := m.(*MyInterface); ok {
		fmt.Println("*MyInterface")
	} else {
		fmt.Println("???")
	}
	fmt.Println()
}

func main() {
	a := TestType1{}
	GetTestName(a)
	GetTestName(&a)

	b := TestType2{}
	GetTestName(b)
	GetTestName(&b)
}

运行结果为

image.png

奇怪的是,对于变量b来说,直接传入结构体,断言失败了,但是对于a来说,不管是指针还是结构体都成功断言

原因是实现接口的方式不一样,对于变量a来说,是结构体TestType1实现的接口,因此即使是传入指针,也会隐式转换为结构体,但是对于变量b来说,是指针实现的接口,因此传入结构体,断言会出错