有没有一种方法可以以两个单词的格式打印字符串变量?

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

Is there a way to print a string variable in its 2 words format?

问题

我想找到一种清晰的方式来具体地证明一个类型为string的变量保存了一个由两个单词构成的数据结构(至少在我理解的范围内是这样)。

这个演示是为了教学目的。

据我所知,一个字符串是一个由两个单词构成的数据结构,其中一个单词保存了底层字节切片的地址,另一个单词保存了长度。

给定一个像这样定义的变量 a := "a string literal",有没有一种方式可以查看(或打印)变量的内容以其两个单词的格式,以便人们实际上可以看到这个由两个单词构成的结构?

英文:

I would like to find a clear way to demonstrate concretely that a variable of type string holds a 2-words data structure (at least as far as I understand it).

This demonstration is for didactic purposes.

So, as I know, a string is a 2 words data structure where one word holds the address of the underlying slice of bytes and the word holds the length.

Given a variable defined like this a := "a string literal", is there a way to view (or print) the content of the variable in its 2 words format so that people can actually see this 2-words structure?

答案1

得分: 2

有没有办法以两个单词的格式查看(或打印)变量的内容?

没有,因为这是一个未指定的实现细节。

如果你可以接受可能会出错的代码:可以使用reflect.StringHeader。请参考unsafe.Pointer点(6)上的方法。

最好不要这样做。正如前面所说:这是一个故意隐藏的实现细节。

英文:

> is there a way to view (or print) the content of the variable in its 2 words format?

No, because this is an unspecified implementation detail.

If you are okay with code that might brake: Use reflect.StringHeader. See unsafe.Pointer point (6) on how to do this.

Best not to do this. As said: this is a deliberately hidden implementation detail.

huangapple
  • 本文由 发表于 2022年9月14日 22:45:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/73718875.html
匿名

发表评论

匿名网友

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

确定