将结构字段转换为字符串

我正在尝试将结构字段“Category”转换为字符串,以便我可以在ConcatatenateNotification中进行串联。

有人知道如何做吗?

请参阅下面的代码片段。


//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


素胚勾勒不出你
浏览 96回答 2
2回答

Qyouu

由于 已经是底层,您可以简单地:Categorystringvalues = append(values, "Category: " + string(n.Category))

万千封印

首先,你不需要strconv。Itoa 要将 int 与字符串连接起来,您可以简单地使用 .如有必要,您可以使用其他动词代替(此处更多)。您可以对 . 是一种更习惯用的方式来连接go中的字符串。fmt.Sprintf("UserID:%v", n.UserID)%vCategoryfmt.Sprintf因此,代码将如下所示://ConcatenateNotification loads data from Notification struct// and concatenates them into one string, "\n" delimitedfunc 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)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go