为什么我得到的是 T 的 ASCII 值而不是 T 字母

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月13日 19:06:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75721049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定