Convert struct field to string

Viewed 2022

I'm trying to convert struct field "Category" to string so that I could do the concatenation in ConcatenateNotification.
Anybody knows how to do it?
Please, see my code snippet below.

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

Since Category is already an underlying string, you can simply:

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

First of all, you dont need strconv.Itoa to concat int with string, you can simply use fmt.Sprintf("UserID:%v", n.UserID). You can use other verb instead of %v(more here) if necessary. And you can use the same approach with Category. fmt.Sprintf is kind of more idiomatic way to concatenate strings in go.

So the code will look something like:

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

If you want to shorten your code, you can also do something like:

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