亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從用作泛型的接口訪問結構屬性

如何從用作泛型的接口訪問結構屬性

Go
慕神8447489 2023-04-17 16:23:08
也許我只是讓我的代碼變得過于復雜,但我正在努力更好地理解接口和結構在 golang 中的工作方式。基本上,我將滿足接口 I 的元素存儲在哈希表中。由于所有滿足 I 的項目都可以包含在 I 元素中,我想我可以將 I 用作一種“通用”接口,將它們填充到哈希圖中,然后稍后將它們拉出并訪問“underlyng”結構方法從那里。不幸的是,在拉出元素后,我發現我無法調用結構方法,因為元素是接口類型,并且“原始”結構不再可訪問。有沒有一種方法可以干凈簡單地訪問滿足我的結構?這是我的代碼,它在 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)    }}
查看完整描述

3 回答

?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

您應該向您的界面添加一個訪問器:


type I interface {

    test()

    Name() string

}

然后確保你的結構實現了這個方法:


func (s S) Name() string {

    return s.name

}

然后使用訪問器方法訪問名稱:


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


查看完整回答
反對 回復 2023-04-17
?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

我認為你需要的是type swithes在旅途中

您可以訪問底層結構,如下所示:


查看完整回答
反對 回復 2023-04-17
?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

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

    }

}


查看完整回答
反對 回復 2023-04-17
  • 3 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號