登录
首页 >  Golang >  Go问答

访问结构体属性的泛型接口使用方法

来源:stackoverflow

时间:2024-03-14 22:54:28 300浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《访问结构体属性的泛型接口使用方法》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

也许我只是让我的代码变得过于复杂,但我试图更好地理解接口和结构在 golang 中的工作原理。

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

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

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

这是我的代码,它在 for 循环内抛出“value.name undefined(类型 i 没有字段或方法名称)”:

/**
 * 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())

我认为你需要的是 type swithestour of go

您可以访问底层结构,如下所示:

for _, value := range testMap {
    switch v := value.(type) {
    case S:
        fmt.Printf("map element name: %s\r\n", v.name)
        // TODO: add other types here
    }
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>