Golang中的Interface、Kind和Variable解析

Golang中的Interface、Kind和Variable解析 在阅读 reflect 包时,我注意到它定义了一个接口类型。

reflect.Interface

我想知道什么样的变量会返回 Interface 类型?我尝试了以下代码,但得到的都是实现接口的数据类型。

package main

import (
	"fmt"
	"reflect"
)

type People interface {
	change_name()
}

type Person struct {
	name string
	age int
}

func main() {
	var a People = Person{"456", 38}
	fmt.Println(reflect.TypeOf(a).Kind())
 }

func (p Person) change_name() {
	p.name = "123"
}

// output: struct

更多关于Golang中的Interface、Kind和Variable解析的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中的Interface、Kind和Variable解析的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,reflect.Interface 表示一个接口类型的变量,而不是实现了接口的具体类型。当你使用 reflect.TypeOf(a).Kind() 时,它返回的是变量 a 的底层具体类型的种类,而不是接口类型本身。

要得到 reflect.Interface 种类,你需要直接对接口类型(而不是接口变量)进行反射。以下是一个示例代码:

package main

import (
	"fmt"
	"reflect"
)

type People interface {
	change_name()
}

type Person struct {
	name string
	age  int
}

func (p Person) change_name() {
	p.name = "123"
}

func main() {
	var a People = Person{"456", 38}
	
	// 获取变量a的类型种类
	fmt.Println("Kind of variable a:", reflect.TypeOf(a).Kind()) // 输出: struct
	
	// 获取接口类型People的种类
	fmt.Println("Kind of interface People:", reflect.TypeOf((*People)(nil)).Elem().Kind()) // 输出: interface
}

输出结果:

Kind of variable a: struct
Kind of interface People: interface

解释:

  • reflect.TypeOf(a).Kind() 返回 struct,因为变量 a 的实际存储值是 Person 结构体实例。
  • 要获取接口类型本身的种类,需要使用 reflect.TypeOf((*People)(nil)).Elem().Kind()
    • (*People)(nil) 创建一个指向 People 接口的 nil 指针
    • .Elem() 获取指针指向的元素类型(即 People 接口类型)
    • .Kind() 返回该类型的种类,即 reflect.Interface

另一种获取接口类型种类的方法是:

var p People
fmt.Println("Kind of interface People:", reflect.TypeOf(&p).Elem().Kind()) // 输出: interface

总结:当变量存储的是接口的具体实现时,reflect.Kind() 返回的是具体类型的种类;要获取接口类型本身的种类,需要对接口类型进行反射操作。

回到顶部