英文:
Where string data goes in memory
问题
我读到字符串是不可变的,内部有两个数据,第一个是指针,第二个是指向的数据的长度。
s := "Hello World"
这意味着s
有两个数据,一个是字符串的字节指针,长度为11。如果我们改变这个数据
s = "This is golang"
那么s
将包含不同的指针和长度,但我不清楚s
指向的字符串字节是存储在堆栈还是堆中?
此外,我们可以从文件中获取字符串并将其赋值给s
变量,这意味着在编译时编译器不会知道要存储的字节数,所以会在堆中吗?
英文:
I read that Strings are immutable and internally string has two data, first one is pointer and second one is length of pointed data.
s := "Hello World"
This means s has two data pointer of bytes of strings and length is 11 and if we change this data
s = "This is golang"
then s
will contain different pointer and length but I am not getting if these bytes of string that s was pointing stored in a stack or in heap?
Also, we can get the string from a file and assign it to s
variable means at compile time compiler won't know the number of bytes to store, so would be heap in?
答案1
得分: 2
字符串字面量存储在数据段中,它们是不可变的。
在运行时动态创建的字符串根据字符串的分配和使用方式,存储在栈上或堆上。如果一个字符串在函数内部使用,并且不会超出该函数的生命周期,那么它很可能存储在栈上。否则,它将存储在堆上。
英文:
String literals are stored in the data segment. They cannot change.
Strings created dynamically at runtime are stored either on stack or in heap, depending on how the strings are allocated/used. If a string is used within a function and does not live beyond that function, it is likely that it will be on stack. Otherwise it will be in heap.
答案2
得分: 0
String
在创建后是不可变的。如果重新分配一个 String
变量,编译器会创建另一个不可变的 String
,丢弃之前的 String
,之前的 String
将等待垃圾回收。
英文:
String
is const after it's been created. If you reassign a String var, the compiler just creates another const String, abandon the previous one, the previous one will wait for GC.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论