打印出 Golang 列表的枚举名称。

huangapple go评论79阅读模式
英文:

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的说法,ab应该被导出(这是正确的答案)。

但是,如果你想保持它们的私有性并且有一个类似的输出,只需在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)
}

huangapple
  • 本文由 发表于 2023年6月28日 00:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76567128.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定