考虑以下函数:
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)
,其中a
和b
是*string
。
如果我将T
修改为*comparable
,将a
和b
修改为T
,我会得到以下错误:cannot 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(认为上述函数应该是可推断的。
有没有一种方法可以使函数取可幂comparable
并使其可推断?或者我做得对吗,但我需要帮助go
发挥作用?
在这种情况下,类型推理只起作用。您根本无法使用文字nil
来推断T
,因为NilCompare(nil, nil)
并没有真正携带类型信息。
要使用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
}