将结构字段转换为字符串

Convert struct field to string

我正在尝试将结构字段“Category”转换为字符串,以便我可以在 ConcatenateNotification 中进行连接。
有人知道怎么做吗?
请看下面我的代码片段。

//Category is enum of
//available notification types (semantic meaning of the notification)
type Category string

// Category allowed values
const (
    FlowFailure  Category = "flow_failure"
    WriterResult Category = "writer_result"
)

//Notification is struct containing all information about notification
type Notification struct {
    UserID     int
    Category   Category

}

//ConcatenateNotification loads data from Notification struct and concatenates them into one string, "\n" delimited
func ConcatenateNotification(n Notification) (msg string) {
    values := []string{}
    values = append(values, "UserID: " + strconv.Itoa(n.UserID))
    values = append(values, "Category: " + (n.Category)) // Anybody knows how to convert this value to string?

    msg = strings.Join(values, "\n")
    return msg

首先,你不需要strconv.Itoa来连接int和string,你可以简单地使用fmt.Sprintf("UserID:%v", n.UserID)。如有必要,您可以使用其他动词代替 %v(more here)。您可以对 Category 使用相同的方法。 fmt.Sprintf 是在 go 中连接字符串的一种更惯用的方式。

所以代码看起来像这样:

//ConcatenateNotification loads data from Notification struct
// and concatenates them into one string, "\n" delimited
func ConcatenateNotification(n Notification) (msg string) {
    values := []string{}
    values = append(values, fmt.Sprintf("UserID: %v", n.UserID))
    values = append(values, fmt.Sprintf("Category: %v", n.Category))
    msg = strings.Join(values, "\n")
    return msg
}

如果你想缩短你的代码,你也可以这样做:

func ConcatenateNotification(n Notification) (msg string) {
    return fmt.Sprintf("UserID: %v\nCategory:%v", n.UserID, n.Category)
}

由于 Category 已经是基础 string,您可以简单地:

values = append(values, "Category: " + string(n.Category))