不管這是否是慣用的 go,在某些情況下,我們希望訪問介面值的底層具體值。這是一個例子:
我有這些結構和介面:
type person struct {
name string
age int
}
type secretAgent struct {
name string
age int
}
type Human interface {
speak()
}
func (p person) speak() {}
func (p secretAgent) speak() {}
我也有這個功能:
func bar(h Human) {
fmt.Println(h.name, "is sent to bar!!") // <-- name is not accessible
}
p1 := person{"foo bar", 34}
bar(p1)
在這種情況下如何訪問結構欄位?
uj5u.com熱心網友回復:
對于任何可能對這個問題感興趣的人,我找到了解決方案。
不管這是否是慣用的方法,因為介面無法找到您嘗試通過它訪問的確切型別,您應該斷言介面值的型別。
型別斷言提供對介面值的底層具體值的訪問。
所以在我的情況下,實作將是這樣的:
func bar(h Human) {
switch h := h.(type) { // <-- this is type assertion
case person:
fmt.Println(h.name, "is sent to bar!!") // <-- just has access to person
case secretAgent:
fmt.Println(h.name, "is sent to bar!!") // <-- has access to secretAgent
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358292.html
標籤:走
上一篇:用go實作冒泡排序
