相关疑难解决方法(0)

为什么Go中有数组?

我理解Go中数组和切片之间的区别.但我不明白的是为什么有数组是有帮助的.为什么数组类型定义指定长度和元素类型有帮助?为什么我们使用的每个"数组"都不能成为切片?

arrays go slice

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

检查值是否在列表中

Go有类似Python的in关键字吗?我想检查一个值是否在列表中.

例如在Python中:

x = 'red'

if x in ['red', 'green', 'yellow', 'blue']:
    print "found"
else:
    print "not found"
Run Code Online (Sandbox Code Playgroud)

在Go中,我想出了使用set惯用法,但我不认为这是理想的,因为我必须指定一个我没有使用的int值.

x := "red"

valid := map[string]int{"red": 0, "green": 0,"yellow": 0, "blue": 0}

if _, ok := valid[x]; ok {
    fmt.Println("found")
} else {
    fmt.Println("not found")
}
Run Code Online (Sandbox Code Playgroud)

我知道有一个in关键字可能与泛型有关.有没有办法使用go generate或其他东西来做到这一点?

dictionary set go

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

如何防止将类型用作地图键?

我有一个可以用作地图键的类型,但我想防止这种情况发生.我假设如果类型包含私有成员,则无法从其他包中进行,但这似乎无论如何都可行.使类型无法用作地图键的最佳方法是什么?

type MyType struct {
    A *A
    b b

    preventUseAsKey ?
}
Run Code Online (Sandbox Code Playgroud)

struct dictionary key unique go

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

使用键作为数组类型的哈希值

如何在Go for map中创建一个键作为数组.例如在ruby中我可以实现它:

quarters = {
  [1, 2, 3] => 'First quarter',
  [4, 5, 6] => 'Second quarter',
  [7, 8 ,9] => 'Third quarter',
  [10, 11, 12] => 'Fourh quarter',
}
quarters[[1, 2, 3]] 
# => "First quarter"
Run Code Online (Sandbox Code Playgroud)

如何在Golang中看到相同的内容?

arrays dictionary go

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

标签 统计

go ×4

dictionary ×3

arrays ×2

key ×1

set ×1

slice ×1

struct ×1

unique ×1