英文:
print enumeration names for a golang list
问题
我有以下枚举类型和它的字符串函数。
当我在特定的Animal值上使用Println时,正确的名称会被打印出来。但是当我将其作为完整列表打印时,只有它们的整数值被打印出来。
如何在打印动物园列表时也打印动物的名称?
package main
import (
"fmt"
)
type Animal int64
const (
Goat Animal = iota
Cat
Dog
)
func (n Animal) String() string {
switch n {
case Goat:
return "Goat"
case Cat:
return "Cat"
case Dog:
return "Dog"
}
return "?"
}
type Group struct {
a, b Animal
}
type Zoo []Group
func main() {
var g1, g2 *Group
g1 = new(Group)
g1.a = Goat
g1.b = Cat
g2 = new(Group)
g2.a = Dog
g2.b = Cat
var z1 Zoo
z1 = []Group{*g1, *g2}
fmt.Println("Animal: ", Dog) // 打印 Dog
fmt.Println(z1) // 打印 [{0 1} {3 1}]
}
英文:
I have the following enumeration, and its string function.
When I use Println on a specific Animal value, the proper
name is printed. But when I print it as a full list, then
only their integer values are printed.
How to print the animal names when I am printing the zoo-list also?
package main
import (
"fmt"
)
type Animal int64
const (
Goat Animal = iota
Cat
Dog
)
func (n Animal) String() string {
switch n {
case Goat:
return "Goat"
case Cat:
return "Cat"
case Dog:
return "Dog"
}
return "?"
}
type Group struct {
a, b Animal
}
type Zoo []Group
func main() {
var g1,g2 *Group
g1 = new(Group)
g1.a = Goat
g1.b = Cat
g2 = new(Group)
g2.a = Dog
g2.b = Cat
var z1 Zoo
z1 = []Group{*g1,*g2}
fmt.Println("Animal: ", Dog) // prints Dog
fmt.Println(z1) // prints [{0 1} {3 1}]
}
答案1
得分: 0
根据@greedy52的说法,a
和b
应该被导出(这是正确的答案)。
但是,如果你想保持它们的私有性并且有一个类似的输出,只需在Group
上实现String()
方法,就像这样:
func (g Group) String() string {
return fmt.Sprintf("{%s %s}", g.a, g.b)
}
英文:
As @greedy52 said a
and b
should exported (it's the right answer).
But if you want to keep them private
and have a similar output, just implement the String()
method on Group
just like that:
func (g Group) String() string {
return fmt.Sprintf("{%s %s}", g.a, g.b)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论