英文:
Why does this conversion in go from a rune-string to integer does not work?
问题
我有以下代码:
我了解Go语言中的符文,我在过去几个小时里阅读了很多关于它们的内容,我试图解决这个问题...
package main
import (
"fmt"
"strconv"
)
func main() {
e := "\x002"
fmt.Println(e)
new := string(e)
i, err := strconv.Atoi(new)
if err != nil { fmt.Println(err) }
fmt.Println(i)
}
结果是:
2
strconv.ParseInt:解析"\x002"时出现无效语法
0
为什么我不能将字符串转换为整数?
任何帮助都将不胜感激!
英文:
i have the following code:
I know about runes in go, i read about them a lot in the last hours i have tried to solve this...
package main
import (
"fmt"
"strconv"
)
func main() {
e := "\x002"
fmt.Println(e)
new := string(e)
i, err := strconv.Atoi(new)
if err != nil { fmt.Println(err) }
fmt.Println(i)
}
result is:
2
strconv.ParseInt: parsing "\x002": invalid syntax
0
why can't i convert the string to an integer?
Any help appreciated!
答案1
得分: 2
我不100%确定你的目标,但看起来你想从包含给定字符的字符串中提取符文的整数值。
你想要的代码如下:
e := "\x02"
runes := []rune(e)
i := runes[0]
fmt.Println(i) // 2
英文:
I'm not 100% sure of your goal but it looks like you want to extract the int value of the rune you get from a string containing a given character.
It looks like you want
e := "\x02"
runes := []rune(e)
i := runes[0]
fmt.Println(i) // 2
答案2
得分: 0
\xXXXX
试图将其解析为Unicode符文,你需要跳过\
检查这里
:
可以使用以下方式:
e := "\x002"
#或者使用原始字符串:
e := `\x002`
编辑:
你为什么认为\x002
是一个有效的整数?你是不是指的是0x002
?
英文:
\xXXXX
tries to parse it as a unicode rune, you need to skip the \
check this
:
Either use :
e := "\\x002"
#or use a raw string :
e := `\x002`
edit :
Why do you think \x002
is a valid integer? do you mean 0x002
?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论