相关疑难解决方法(0)

为什么我可以键入别名函数并使用它们而不进行转换?

在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)

types casting go

86
推荐指数
2
解决办法
4万
查看次数

map[gorm.DB]struct{}{} 给出无效的地图键类型 gorm.DB

我想创建一组在我的应用程序中使用的 gorm 类型。所以我想map用我的类型定义 agorm.DB作为键,空structs{}作为标志:

var (
    autoMigrations map[gorm.DB]struct{}
)
Run Code Online (Sandbox Code Playgroud)

但是编译器不允许我用错误来做这个:invalid map key type gorm.DB. 我可以使用指向gorm.DBs 的指针来愚弄它,例如:

map[*gorm.DB]struct{}
Run Code Online (Sandbox Code Playgroud)

但这不是解决方案,因为我需要使它独一无二,如果我的地图被填满,db.AutoMigrate(&Chat{})我可以获得许多具有不同地址的类似对象。

另一种解决方案是制作一片gorm.DB

autoMigrations []gorm.DB
Run Code Online (Sandbox Code Playgroud)

但是我必须手动过滤元素,这似乎有点疯狂。

dictionary key go hashable go-gorm

5
推荐指数
1
解决办法
4334
查看次数

在 Golang 中检查 IP 地址切片中的 IP 的有效方法

我正在 Golang 中开发一个网络应用程序。我有一个 IP 地址片段。每次收到请求时,我都会用来net.LookupIP(host)查找返回net.IP. 比较这些的最佳方法是什么?

顺便说一句,在 Python 中我们有一个set数据结构,这使得上面的问题很容易解决,但是 Go 呢?

arrays ip network-programming go slice

1
推荐指数
1
解决办法
4318
查看次数

标签 统计

go ×3

arrays ×1

casting ×1

dictionary ×1

go-gorm ×1

hashable ×1

ip ×1

key ×1

network-programming ×1

slice ×1

types ×1