2 回答

TA貢獻(xiàn)1805條經(jīng)驗 獲得超10個贊
您不能==在接口值上使用相等運(yùn)算符。即使動態(tài)類型相同,如果它們具有不同值的字段,比較也可能返回 false。或者它會恐慌 if B,C并且D與開始時不可比較。
相反,您可以使用反射并使用==on reflect.Type。如果您添加更多實現(xiàn)A.
func dynamicTypesEq(args []A) bool {
var a reflect.Type
for _, d := range args {
t := reflect.TypeOf(d)
if a == nil {
a = t
continue
}
if a != t {
return false
}
}
return true
}
使用一些示例切片調(diào)用函數(shù):
func main() {
a := []A{&B{}, &B{}, &B{}}
fmt.Println(dynamicTypesEq(a)) // true
b := []A{&C{}, &B{}, &B{}}
fmt.Println(dynamicTypesEq(b)) // false
c := []A{&D{}, &D{}, &B{}}
fmt.Println(dynamicTypesEq(c)) // false
}
請注意,如果輸入具有*B和,則此函數(shù)報告錯誤B。顯然,指針類型與基類型不同。
游樂場:https ://go.dev/play/p/QOCvSyxGPRU

TA貢獻(xiàn)1780條經(jīng)驗 獲得超5個贊
這是使用 reflect 包的方法。如果某個元素的類型與第一個元素的類型不同,則切片包含混合值類型。
func check(args []interface{}) bool {
if len(args) == 0 {
return true
}
t := reflect.TypeOf(args[0])
for _, v := range args[1:] {
if reflect.TypeOf(v) != t {
return false
}
}
return true
}
以下是如何在沒有反射的情況下做到這一點。保留一個狀態(tài)變量,記錄最后看到的類型。如果當(dāng)前類型不是最后一個類型,則切片包含混合值類型。
func check(args []interface{}) bool {
const (
initState = iota
typeB
typeC
typeD
)
state := initState
for _, d := range args {
switch d.(type) {
case *B:
if state != initState && state != typeB {
return false
}
state = typeB
case *C:
if state != initState && state != typeC {
return false
}
state = typeC
case *D:
if state != initState && state != typeD {
return false
}
state = typeD
default:
panic("unsupported type")
}
}
return true
}
- 2 回答
- 0 關(guān)注
- 159 瀏覽
添加回答
舉報