慕姐4208626
声明一段字符串,其中字符串对应于常量名称:var animalNames = []string{ "Dog", "Cat", "Fish", "Horse", "Snake", "Rabbit", "Lion", "Rino", "Hedgehog",}要获取位的名称,请循环遍历名称。如果设置了相应的位,则将名称添加到结果中:func Names(k Key) []string { var result []string for i := 0; i < len(animalNames); i++ { if k&(1<<uint(i)) != 0 { result = append(result, animalNames[i]) } } return result}在操场上运行它。如果将常量更改为位索引而不是位值,则可以使用stringer实用程序创建一个func (k Key) String() string. 这是此更改的代码:type Key uintconst ( Dog Key = iota Cat Fish Horse Snake Rabbit Lion Rino Hedgehog)//go:generate stringer -type=Keyfunc Names(k Key) []string { var result []string for animal := Dog; animal <= Hedgehog; animal++ { if k&(1<<animal) != 0 { result = append(result, animal.String()) } } return result}