2

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
  • You might want to use fmt.Sprintf("%v", n.Category). I think it will solve your problem. Commented Apr 1, 2021 at 9:43
  • 1
    @Giannis that's way overkill, Category is already a string type. Commented Apr 1, 2021 at 14:27

2 Answers 2

4

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

values = append(values, "Category: " + string(n.Category))
Sign up to request clarification or add additional context in comments.

1 Comment

You are right Adrian. Your solution is more elegant. Cheers mate!
1

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

1 Comment

"fmt.Sprintf is kind of more idiomatic way to concatenate strings in go" - not really. It's the more idiomatic way to format strings (hence the name). The idiomatic way to concatenate strings is with the concatenation operator +.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.