dota220141003 2018-10-05 10:02
浏览 135
已采纳

如何从用作泛型的接口访问struct属性

Maybe i am just over complicating my code but i am trying to get a better understanding of how interfaces and structs work in golang.

Basically, i am storing elements that satisfy interface I inside an hash table. As all the items that satisfy I can be contained inside an I element, i thought i could be using I as a kind of "generic" interface, stuff them inside a hashmap, then pull them out later and access the "underlyng" struct methond from there.

Unfortunately, after pulling the element out, i found out that i cannot call the struct method, as element is of Interface type, and the "original" struct is not accessible anymore.

Is there a way to get a clean and simple access to the struct that satisfy I?

This is my code, it throws a "value.name undefined (type I has no field or method name)" inside the for loop:

/**
 * 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
", 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
", value.name)
    }

}
  • 写回答

2条回答 默认 最新

  • douhengdao4499 2018-10-05 10:55
    关注

    You should add an accessor to your interface:

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

    Then make sure your struct implements this method:

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

    And then access the name using the accessor method:

            fmt.Printf("map element name: %s
    ", value.Name())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址