小编AJR*_*AJR的帖子

我可以有一个函数来检查一个键是否在地图中吗?

我想要一个像Map.containsKey()Go一样的功能,因为 Go 本身不提供这种功能,我可以像MapContainsKey(someMap map[K]V, key K)Go一样拥有一个自定义功能吗?

我不知道如何实现它,因为据我所知,Go 中还没有泛型。

我知道我能做到

if val, ok := someMap[key]; ok{
   // some code here
}
Run Code Online (Sandbox Code Playgroud)

但我想将它包装在一个函数中。

dictionary go

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

切片数组文字

我认为 Go 规范存在一个小问题。以下抱怨数组文字不可寻址:

    print([4]int{2,3}[:2])
Run Code Online (Sandbox Code Playgroud)

我知道为什么从函数返回的数组不可寻址(例如,对函数返回的切片进行寻址时出错),但为什么数组文字像[4]int{2,3}不可寻址一样?特别是当切片和字符串文字是 - 例如这些工作正常:

    print([]int{2,3,0,0}[:2])
    print("2300"[:2])
Run Code Online (Sandbox Code Playgroud)

此外,数组文字似乎是可寻址的,因为它&[4]int{42,43}是一个有效的表达式。

我知道我可以用切片

    print([]int{2,3,0,0}[:2])
Run Code Online (Sandbox Code Playgroud)

但是如果我希望容量(数组长度)是一个编译时常量呢?

    const maxLength = 4
    ...
    print([maxLength]int{2,3}[:2])
Run Code Online (Sandbox Code Playgroud)

是的,我可以分配给一个临时数组变量,但为什么我需要?

arrays go slice

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

Go vet 关于忽略上下文取消功能的警告

我将超时上下文传递给 Server.Shutdown (http 包)。我不认为我需要调用返回的取消函数,所以我忽略它。但当我跑去看兽医时,它说the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

如果没有问题,如何解决问题或避免出现 go vet 错误消息?

    go signalShutdown(server, stopCh)

    if err := server.ListenAndServeTLS(cert, key); err != http.ErrServerClosed {
        log.Fatalf("ListenAndServeTLS() error: %v\n", err)
    }
    // Note: exit here does not terminate main()
}

// signalShutdown waits for a notification from the OS that the http server
// should be shutdown, then gracefully stops it.
func signalShutdown(server *http.Server, stopCh <-chan struct{}) {
    const …
Run Code Online (Sandbox Code Playgroud)

go

-3
推荐指数
1
解决办法
1570
查看次数

标签 统计

go ×3

arrays ×1

dictionary ×1

slice ×1