gpt4 book ai didi

反射式没有方法

转载 作者:IT王子 更新时间:2023-10-29 02:05:54 25 4
gpt4 key购买 nike

我正在尝试在 Go 中使用反射。为什么这段代码没有列出方法?它列出了字段。

这是问题吗? value interface{} 我不确定如何将通用结构/类/类型传递给函数。通常我只会传递一个对象。

(我对此完全陌生。我是一名 C# 程序员)

package main

import (
"fmt"
"reflect"
)

func main() {
var B TestType = TestType{TestString: "Hello", TestNumber: 3}
ListMethods(B)
}

func ListMethods(value interface{}) {

fooType := reflect.TypeOf(value)

for i := 0; i < fooType.NumMethod(); i++ {
method := fooType.Method(i)
fmt.Println("Method = " + method.Name)
}

for i := 0; i < fooType.NumField(); i++ {
field := fooType.Field(i)
fmt.Println("Field = " + field.Name)
fmt.Println(reflect.ValueOf(value).Field(i))
}
}

type TestType struct {
TestString string
TestNumber int
}

func (this *TestType) TestFunction() {
fmt.Println("Test")
}

最佳答案

因为您正在传递一个类型,并且您声明了一个指向该类型指针的方法。

https://play.golang.org/p/B0NdVyxGxt

看看这个从你的扩展而来的例子:

package main

import (
"fmt"
"reflect"
)

func main() {
var B TestType = TestType{TestString: "Hello", TestNumber: 3}
ListMethods(B)
}

func ListMethods(value interface{}) {

fooType := reflect.TypeOf(value)
ptrFooType := reflect.PtrTo(fooType)

for i := 0; i < fooType.NumMethod(); i++ {
method := fooType.Method(i)
fmt.Println("Method = " + method.Name)
}

for i := 0; i < ptrFooType.NumMethod(); i++ {
method := ptrFooType.Method(i)
fmt.Println("* Method = " + method.Name)
}

for i := 0; i < fooType.NumField(); i++ {
field := fooType.Field(i)
fmt.Println("Field = " + field.Name)
fmt.Println(reflect.ValueOf(value).Field(i))
}
}

type TestType struct {
TestString string
TestNumber int
}

func (this *TestType) TestFunctionPtr() {
fmt.Println("Test")
}

func (this TestType) TestFunction() {
fmt.Println("Test Non Ptr")
}

注意 *Type 如何也可以访问 Type 方法。但是 Type 无法访问 *Type 方法。

要从 Type 转换为 *Type,我使用了 reflect.PtrTo(Type)

关于反射式没有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25564403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com