也許我只是讓我的代碼變得過于復雜,但我正在努力更好地理解接口和結構在 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())

慕姐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
}
}
- 3 回答
- 0 關注
- 143 瀏覽
添加回答
舉報
0/150
提交
取消