gpt4 book ai didi

go - 如何从用作泛型的接口(interface)访问结构属性

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

也许我只是让我的代码过于复杂,但我正试图更好地理解接口(interface)和结构在 golang 中的工作方式。

基本上,我将满足接口(interface) I 的元素存储在哈希表中。由于所有满足 I 的项目都可以包含在 I 元素中,我想我可以将 I 用作一种“通用”接口(interface),将它们填充到 HashMap 中,然后稍后将它们拉出并访问“underlyng”结构方法从那里。

不幸的是,在拉出元素后,我发现我无法调用结构方法,因为元素是接口(interface)类型,“原始”结构不再可用。

有没有一种方法可以干净简单地访问满足 I 的结构?

这是我的代码,它在 for 循环中抛出一个“value.name undefined (type I has no field or method name)”:

/**
* Define the interface
*/
type I interface{
test()
}

/**
* Define the struct
*/
type S struct{
name string
}

/**
* S now implements the I interface
*/
func (s S) test(){}

func main(){

/**
* Declare and initialize s S
*/
s := S{name:"testName"}

/**
* Create hash table
* It CAN contains S types as they satisfy I interface
* Assign and index to s S
*/
testMap := make(map[string]I)
testMap["testIndex"] = s

/**
* Test the map length
*/
fmt.Printf("Test map length: %d\r\n", len(testMap))

for _, value := range testMap{

/**
* This is where the error is thrown, value is of Interface type, and it is not aware of any "name" property
*/
fmt.Printf("map element name: %s\r\n", value.name)
}

}

最佳答案

您应该向您的界面添加一个访问器:

type I interface {
test()
Name() string
}

然后确保你的结构实现了这个方法:

func (s S) Name() string {
return s.name
}

然后使用访问器方法访问名称:

        fmt.Printf("map element name: %s\r\n", value.Name())

关于go - 如何从用作泛型的接口(interface)访问结构属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52663100/

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