Why when you print this fmt.Println("Hello world"[1])
I get 101 instead of e
Can someone explain this to me please
评论:
rauyran:
Diddyshyne120:"Hello world"[1] returns a byte. The byte representing 'e' is 101
adamtanner:This might be a stupid question, I don't get where the 101 came. Can you explain a lil bit more I can understand it. I'm very new to this.
HelperBot_:Go source code (and thus string literals) is defined to be UTF-8 encoded. Each code point (character) is represented by a sequence of 1-4 bytes. The code point for "e" is represented by a single byte with the value "01100101". When you interpret that byte as decimal you get the number "101".
You will often find the specific byte patterns represented as hexidecimal numbers rather than a decimals, so you may also see places that refer to "e" as "65".
https://en.m.wikipedia.org/wiki/UTF-8
https://blog.golang.org/strings
a_k_w:Non-Mobile link: https://en.wikipedia.org/wiki/UTF-8
HelperBot v1.1 /r/HelperBot_ I am a bot. Please message /u/swim1929 with any feedback and/or hate. Counter: 89060
mrxinu:there is a difference between typed and raw strings, and in this context that means something.
nuulss:Have a look at my reply on your Twitter. Hope this helps!
Diddyshyne120:when indexing strings, you get a single byte which can be converted back to a string https://play.golang.org/p/JQhAl7mI2V https://golang.org/ref/spec#String_types
jimijiim:Returned the value for the whole of the string which equal to 101?
abhayakara:https://golang.org/ref/spec#String_types
A string's bytes can be accessed by integer indices 0 through len(s)-1.
The string is stored as a sequence of numbers in an array. The numbers are ASCII (in this case) or utf-8 (more generally).
So the array that is that string contains: 72 101 108 108 111 32 119 111 114 108 100
As you can see, the 1th element (the second, because the 0th element is the first) is 101.
