Search code examples
gostructstring-conversion

Convert struct field to string


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

Solution

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

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