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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示