dongyangzhi0687 2013-07-26 18:13
浏览 66
已采纳

有什么办法可以判断Go中两个字符串是否共享内存?

In Go, strings are stored internally as the C-struct:

struct String // This is C code (not Go)
{
  byte* str;
  int32 len;
};

Let's say I have the following variables:

a0 := "ap" // This is Go code
a1 := "ple"
b0 := "app"
b1 := "le"
a := a0 + a1
b := b0 + b1
c := "apple"
d := c

Then the following code:

fmt.Println("a == b = %t, &a == &b = %t", a == b, &a == &b)
fmt.Println("c == d = %t, &c == &d = %t", c == d, &c == &d)

outputs:

a == b = true, &a == &b = false
c == d = true, &c == &d = false

because &a == &b compares the addresses of the C-structs, while a == b compares the values of the strings.

Is there any way to test whether the strings themselves are stored in the same place (i.e. the str field in the C-struct has the same value), such that comparing a and b would most likely yield false, while comparing c and d would almost certainly yield true?

  • 写回答

2条回答 默认 最新

  • dqwh0109 2013-07-26 19:12
    关注

    Yes, it's possible. Use the reflect package and obtain the String Headers of two string instances. Then you can compare both the Data and Len fields to compute whether the string backing arrays do overlap in memory.

    Note: The StringHeader struct is an implementation detail, it's not mentioned by the language specs. Thus, any code doing things like discussed in the above paragraph is not really portable Go. IOW, I discourage to use such code outside of curiosity/research etc. From the docs:

    StringHeader is the runtime representation of a string. It cannot be used safely or portably and its representation may change in a later release. Moreover, the Data field is not sufficient to guarantee the data it references will not be garbage collected, so programs must keep a separate, correctly typed pointer to the underlying data.

    EDIT:

    Untested code to obtain a *reflect.StringHeader hdr from a string instance str:

    hdr := (*reflect.StringHeader)(unsafe.Pointer(&str))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?