英文:
Why I am getting the ASCII value of T instead of the T letter
问题
我有以下代码:
package main
import (
"fmt"
)
func main() {
book := "The_colour_of_magic"
fmt.Println(book[0])
}
当我执行这段代码时,我得到的结果是84(T字母的ASCII值)。
请问为什么我得到的答案是84而不是T。
英文:
I have this below code:
package main
import (
"fmt"
)
func main() {
book := "The_colour_of_magic"
fmt.Println(book[0])
}
When I am executing this code, I am getting the result as 84 (ASCII value of T alphabet).
May I know why I am getting the answer as 84 instead of T.
答案1
得分: 4
根据定义,字符串是字节的切片,而字节本质上是无符号8位整数(uint8)。
当你引用book[0]时,你引用的是一个字节,即uint8类型。
尝试添加以下代码行以查看book[0]的类型:
fmt.Printf("book[0]的类型:%T", book[0])
由于你试图打印book[0]中的值,它将打印字节中的无符号整数值。
英文:
By definition string is a slice of bytes and byte is nothing but unsigned int 8 (uint8)
When you are referring to book[0] you are referring a byte and it uint8.
try adding this line to see type of book[0]
fmt.printf("Type of book[0]:%T", book[0])
As you are attempting to print value in book[0], it will print Unisgned Integer value in the byte.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论