2

I got slightly confused this morning when the following code worked.

// s points to an empty string in memory
s := new(string)

// assign 1000 byte string to that address
b := make([]byte, 0, 1000)
for i := 0; i < 1000; i++ {
    if i%100 == 0 {
        b = append(b, '\n')
    } else {
        b = append(b, 'x')
    }
}
*s = string(b)

// how is there room for it there?
print(*s)

http://play.golang.org/p/dAvKLChapd

I feel like I'm missing something obvious here. Some insight would be appreciated.

4
  • 1
    The line *s = string(b) assigns s to a new string. This discards the old object you made in your second line. Commented Apr 19, 2013 at 14:28
  • @FUZxxl I was thinking in terms of C strings, which seems obviously wrong in retrospect. Commented Apr 19, 2013 at 14:31
  • 2
    In Go, a string is already a reference type, just as a slice is. Commented Apr 19, 2013 at 14:34
  • To make it simpler, you can just consider t := ""; t = string(b); print(t) // how is there room for it there? where t is the *s Commented Apr 19, 2013 at 17:35

1 Answer 1

8

I hope I understood the question...

An entity of type string is implemented by a run time struct, roughly

type rt_string struct {
        ptr *byte // first byte of the string
        len int   // number of bytes in the string
}

The line

*s = string(b)

sets a new value (of type rt_string) at *s. Its size is constant, so there's "room" for it.

More details in rsc's paper.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.