考慮以下函式:
func NilCompare[T comparable](a *T, b *T) bool {
if a == nil && b == nil {
// if both nil, we consider them equal
return true
}
if a == nil || b == nil {
// if either is nil, then they are clearly not equal
return false
}
return *a == *b
}
此功能有效。但是,當我呼叫它時,我必須提供型別,因為 Go 無法推斷 ( cannot infer T) 它,例如NilCompare[string](a, b)wherea和bare *string。
如果我修改T為 be*comparable和to be a,則會收到此錯誤:
bTcannot use type comparable outside a type constraint: interface is (or embeds) comparable
我正在使用 Go 1.19.2。
$ go version
go version go1.19.2 linux/amd64
具有諷刺意味的是,我的 IDE(GoLand 2022.2.3)認為上述功能應該是可推斷的。
有沒有辦法讓一個函式可以取 nillablecomparable并使其可推斷?還是我做對了,但我需要幫助這個go功能?
uj5u.com熱心網友回復:
在這種情況下,型別推斷才有效。您根本無法T使用 literal推斷nil,NilCompare(nil, nil)因為它并沒有真正攜帶型別資訊。
要使用 s 測驗您的功能,nil請執行以下操作:
package main
import "fmt"
func main() {
var a *string = nil
var b *string = nil
// a and b are explicitly typed
res := NilCompare(a, b) // T inferred
fmt.Println(res) // true
}
這也可以:
func main() {
// literal nil converted to *string
res := NilCompare((*string)(nil), (*string)(nil)) // T inferred
fmt.Println(res) // true
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511202.html
標籤:去仿制药
上一篇:呼叫具有匹配泛型引數的泛型函式
下一篇:如何在Expression<Func<T,TResult?>中轉換可以是物件或List<object>的TResult?
