Help understanding this. I'm new to programming

xuanbao · 2017-07-10 21:00:01 · 668 次点击    
这是一个分享于 2017-07-10 21:00:01 的资源,其中的信息可能已经有所发展或是发生改变。

Why when you print this fmt.Println("Hello world"[1])

I get 101 instead of e

Can someone explain this to me please


评论:

rauyran:

"Hello world"[1] returns a byte. The byte representing 'e' is 101

Diddyshyne120:

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.

adamtanner:

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

HelperBot_:

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

a_k_w:

there is a difference between typed and raw strings, and in this context that means something.

mrxinu:

Have a look at my reply on your Twitter. Hope this helps!

https://twitter.com/mrxinu/status/883730005691322368

nuulss:

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

Diddyshyne120:

Returned the value for the whole of the string which equal to 101?

jimijiim:

https://golang.org/ref/spec#String_types

A string's bytes can be accessed by integer indices 0 through len(s)-1.

abhayakara:

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.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

668 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传