英文:
Converting Integer to String in url.Query().Set using String function
问题
这是我使用Go语言的第一天,我目前正在尝试获取数据,但遇到了一个错误,即将整数转换为字符串。
你可以尝试以下代码,结果是:
实际结果:
https://jsonmock.hackerrank.com/api/movies/search/?page=%01&title=spiderman
期望结果:
https://jsonmock.hackerrank.com/api/movies/search/?page=1&title=spiderman
出现了%01,这是我不想要的。我相信我在将整数转换为字符串时犯了一个错误。
英文:
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
得分: 1
你应该使用strconv.Itoa()方法将整数格式化为字符串。这在链接的答案中有更详细的解释。为了完整起见,这里是你的结果中出现%01
的原因:
- 首先,整数
1
按照这个转换规则被“简单转换”为字符串:
> 将有符号或无符号整数值转换为字符串类型会产生一个包含整数的UTF-8表示的字符串。超出有效Unicode代码点范围的值会被转换为“\uFFFD”。
- 然后,结果字符串(具有Unicode代码点等于1的字符)被URL编码,最终以
%01
表示。
作为附注,如果你在代码中运行go vet,你会收到警告:
> hello.go:19:20: 将整数转换为字符串会产生一个由一个符文组成的字符串,而不是由数字组成的字符串(你是不是想使用fmt.Sprint(x)?)
虽然这并不总是给出如何修复错误的最佳建议,但至少它将你引导到了正确的方向。强烈建议从学习语言的第一天开始就习惯运行这种(或类似的)检查。
英文:
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.
<hr>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论