在Golang中创建一个已知文本字符串的字节切片可以使用以下代码:

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

Creating a byte slice with a known text string, in Golang

问题

我有这段文本,我想将其放入一个字节切片中:

s := "There are these two young fish swimming along and they happen to meet an older fish swimming the other way"

如果我写成:

b := []byte("There are these two young fish swimming along and they happen to meet an older fish swimming the other way")

据我了解,在运行时,这将会:

  1. 创建一个存储在内存中的字符串
  2. 创建一个字节切片
  3. 将字符串的内容复制到字节切片中(根据需要重新分配内存)

我可以将每个字符串值转换为它们的ASCII等效值,并直接创建字节切片:

b := []byte{84, 104, ... }

尽管这种方式不太易读。

我了解到这个例子有点琐碎,大多数计算机可以立即完成这个操作,但我对此很好奇。编译器是否会解释[]byte("blah")并在编译时将其转换为高效的字节切片?如果字符串包含非ASCII字符,最佳解决方案是否会改变?

英文:

I have this text which I would like to put into a byte slice:

s := "There are these two young fish swimming along and they happen to meet an older fish swimming the other way"

If I write

b := []byte("There are these two young fish swimming along and they happen to meet an older fish swimming the other way")

As I understand, at runtime this will:

  1. create a string with the values in memory
  2. create a byte slice
  3. copy the contents of the string into the byte slice (reallocating as necessary)

I could convert each of the string values to their ASCII equivalent and create the byte slice directly:

b := []byte{84, 104, ... }

though this isn't very readable.

I understand that the example here is a little trivial and most computers can do this in a flash, but I'm curious about it. Does the compiler interpret []byte("blah") and turn it into an efficient byte slice at compile time? Would the best solution change if the string included non-ASCII characters?

答案1

得分: 5

Go将字符串作为字符串字面量嵌入可执行程序中。它使用runtime.stringtoslicebyte函数在运行时将字符串字面量转换为字节切片。

英文:

Go embeds the string in the executable program as a string literal. It converts the string literal to a byte slice at runtime using the runtime.stringtoslicebyte function.

答案2

得分: 4

如果你从一个常量字符串初始化一个[]byte变量,编译器似乎足够聪明,不会创建一个中间字符串:相反,字节切片的支持数组直接从静态数据初始化,而不是首先构造一个字符串变量。

虽然存在数据复制,但这在构造可变类型时是可以预期的。

英文:

If you are initialising a []byte variable from a constant string, it looks like the compiler is smart enough not to create an intermediate string: instead, the backing array for the byte slice is initialised directly from static data rather than constructing a string variable first.

There is a data copy, but that is to be expected when constructing a mutable type.

huangapple
  • 本文由 发表于 2014年9月6日 02:28:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/25691879.html
匿名

发表评论

匿名网友

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

确定