Converting Integer to String in url.Query().Set using String function


this is my day 1 using goLang, I am currently trying to consume a data but I encounter an error, and that’s converting integer to string

func createLink(title string, page int) string {
    url := url.URL{
        Scheme: "https",
        Host:   "",
        Path:   "/api/movies/search/",
    query := url.Query()
    query.Set("page", string(page))
    query.Set("title", title)
    url.RawQuery = query.Encode()
    return url.String()

you can try that code, and the result is
actual result :

expected result :

There’s %01 , an that’s something that I do not want. i believe that I made a mistake in converting an integer to string


You should use strconv.Itoa() method to format your integers as strings. This is better explained in the linked answer. For the sake of completeness, here’s how you end up with %01 in your result:

  • first, int 1 gets "plain-converted" to string by following this conversion rule:

Converting a signed or unsigned integer value to a string type yields
a string containing the UTF-8 representation of the integer. Values
outside the range of valid Unicode code points are converted to

  • then the resulting string (with character of unicode code point equal to 1) gets URL-encoded, ending up with %01 as its representation.

As a sidenote, you’re warned about this if you run go vet over your code:

hello.go:19:20: conversion from int to string yields a string of one
rune, not a string of digits (did you mean fmt.Sprint(x)?)

While this doesn’t always give you absolutely the best advice on how to fix your error, it at least pushed you into the right direction. And it’s strongly recommended to get used to the idea of running this (or similar) kind of checks from day 1 of learning language.

Answered By – raina77ow

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.