在Go中,如果您定义一个新类型,例如:
type MyInt int
Run Code Online (Sandbox Code Playgroud)
然后,您无法将a传递MyInt
给期望int的函数,反之亦然:
func test(i MyInt) {
//do something with i
}
func main() {
anInt := 0
test(anInt) //doesn't work, int is not of type MyInt
}
Run Code Online (Sandbox Code Playgroud)
精细.但是为什么同样不适用于功能呢?例如:
type MyFunc func(i int)
func (m MyFunc) Run(i int) {
m(i)
}
func run(f MyFunc, i int) {
f.Run(i)
}
func main() {
var newfunc func(int) //explicit declaration
newfunc = func(i int) {
fmt.Println(i)
}
run(newfunc, 10) //works just fine, even though types seem to differ
} …
Run Code Online (Sandbox Code Playgroud) 我想创建一组在我的应用程序中使用的 gorm 类型。所以我想map
用我的类型定义 agorm.DB
作为键,空structs{}
作为标志:
var (
autoMigrations map[gorm.DB]struct{}
)
Run Code Online (Sandbox Code Playgroud)
但是编译器不允许我用错误来做这个:invalid map key type gorm.DB
. 我可以使用指向gorm.DB
s 的指针来愚弄它,例如:
map[*gorm.DB]struct{}
Run Code Online (Sandbox Code Playgroud)
但这不是解决方案,因为我需要使它独一无二,如果我的地图被填满,db.AutoMigrate(&Chat{})
我可以获得许多具有不同地址的类似对象。
另一种解决方案是制作一片gorm.DB
:
autoMigrations []gorm.DB
Run Code Online (Sandbox Code Playgroud)
但是我必须手动过滤元素,这似乎有点疯狂。
我正在 Golang 中开发一个网络应用程序。我有一个 IP 地址片段。每次收到请求时,我都会用来net.LookupIP(host)
查找返回net.IP
. 比较这些的最佳方法是什么?
顺便说一句,在 Python 中我们有一个set
数据结构,这使得上面的问题很容易解决,但是 Go 呢?