[runtime] gostring question

100 views
Skip to first unread message

Bill Morgan

unread,
Jun 23, 2020, 8:32:56 PM6/23/20
to golang-nuts
I'm a C programmer so maybe this is a dumb question but, why does this code in runtime/gostring.go allocate (rawstring) then copy data (memmove) instead of just making the stringStruct.str point at the incoming data? i.e. copy the pointer instead of allocating+copying data.


func gostring(p *byte) string {
l := findnull(p)
if l == 0 {
return ""
}
s, b := rawstring(l)
memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
return s
}

Bill Morgan

unread,
Jun 23, 2020, 8:48:49 PM6/23/20
to golang-nuts
looks like the code came from commit: 61dca94e107170d2ff3beb13bb9fa5ce49d8d6fd and the old string.c file had a gostringnocopy that copied the ptr instead of allocating and copying. 

Wondering why that was removed. I guess there must be some reason that you must have a duplicate copy.

 

Kurtis Rader

unread,
Jun 23, 2020, 8:52:23 PM6/23/20
to Bill Morgan, golang-nuts
On Tue, Jun 23, 2020 at 5:32 PM Bill Morgan <arthurwil...@gmail.com> wrote:
I'm a C programmer so maybe this is a dumb question but, why does this code in runtime/gostring.go allocate (rawstring) then copy data (memmove) instead of just making the stringStruct.str point at the incoming data? i.e. copy the pointer instead of allocating+copying data.

Go strings are immutable: https://golang.org/ref/spec#String_types.

--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

keith....@gmail.com

unread,
Jun 24, 2020, 7:35:37 PM6/24/20
to golang-nuts
Yes, we can't depend on the data at *p to remain constant. We need to snapshot it at the moment of the gostring call.
Reply all
Reply to author
Forward
0 new messages