-2

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:   "jsonmock.hackerrank.com",
        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 :

https://jsonmock.hackerrank.com/api/movies/search/?page=%01&title=spiderman

expected result :

https://jsonmock.hackerrank.com/api/movies/search/?page=1&title=spiderman

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

1 Answers1

1

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 "\uFFFD".

  • 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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229