In the smippet herunder, are strings copied or passed by address (they seem copied, but maybe only the addresses are copied) ?

51 views
Skip to first unread message

Serge Hulne

unread,
Aug 1, 2020, 10:49:33 AM8/1/20
to golang-nuts
```
package main

import (
    "fmt"
)

func f(s *string) {
    a := "Hello"
    b := "Hello"
    c := "bye"
    d := a
    fmt.Printf("pa: %p\n", &a)
    fmt.Printf("pb: %b\n", &b)
    fmt.Printf("pc: %v\n", &c)
    fmt.Printf("pd: %v\n", &d)
    fmt.Printf("p(f(u)): %p\n", s)
}

func main() {
    u := "test"
    fmt.Printf("pu: %p\n", &u)
    f(&u)
}
```

Jan Mercl

unread,
Aug 1, 2020, 12:00:36 PM8/1/20
to Serge Hulne, golang-nuts
Please post code as just text. Also, inverted color schemes are hard to read for some people.

Wrt string copying, see https://research.swtch.com/godata

to;dr Copying a string copies two machine words.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e31f6d86-ce19-4c81-8ac9-a62f0c7b3bc7o%40googlegroups.com.

Brian Candler

unread,
Aug 1, 2020, 1:48:50 PM8/1/20
to golang-nuts
In Go, everything is passed by value: that is, assignments and function calls make a copy of the value.

However, some types are effectively structs which contain pointers embedded within them.  Strings, slices, maps, channels and interface values fall into this category.

string is roughly equivalent to:

struct {
    ptr *byte  // immutable
    len int
}

[]byte is roughly equivalent to:

struct {
    buf *byte
    len int
    cap int
}

When you assign one of these values, or pass it as a parameter to a function, then the struct is copied by value - e.g. if the struct is 16 bytes then you're copying 16 bytes - but both copies contain a pointer to the same underlying data (which could be larger or smaller).

Serge Hulne

unread,
Aug 1, 2020, 2:04:46 PM8/1/20
to golang-nuts
Thank you!
Reply all
Reply to author
Forward
0 new messages