Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of passing a pointer to a strings in go (golang)?

I was reading the following conversation about go (golang) strings. Strings in go are just a pointer to a (read-only) array and a length. Thus, when you pass them to a function the pointers are passed as value instead of the whole string. Therefore, it occurred to me, if that is true, then why are you even allowed to define as a function with a signature that takes *string as an argument? If the string is already doing plus, the data is immutable/read-only, so you can't change it anyway. What is the point in allowing go to pass pointers to strings if it already does that internally anyway?

like image 694
Charlie Parker Avatar asked Jul 08 '14 22:07

Charlie Parker


People also ask

What is a pointer in Golang?

Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format (starting with 0x like 0xFFAAF etc.).

Can you pass array as a function parameter in Golang?

But passing array pointer as function parameter is not idiomatic to Go. We should prefer slices instead for this functionality. As we saw in the slices lesson, we can pass a slice as an argument to a function and that function can mutate the values inside the slice.

What is the significance of memory address 0 in Golang?

However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the nil (zero) value, it is assumed to point to nothing. Pointers have many but easy concepts and they are very important to Go programming.

Can you point to a pointer in go?

Pointer to pointer in GoLang A pointer variable can store even a pointers address since a pointer is also a variable just like others. So, we can point to a pointer and create levels of indirection. These levels of indirection can sometimes create unnecessary confusion so be wary when using it. 6. Pointer to interfaces


1 Answers

You pass a pointer to the "object" holding the string so that you can assign a different string to it.

Example: http://play.golang.org/p/Gsybc7Me-5

func ps(s *string) {
    *s = "hoo"
}
func main() {
    s := "boo"
    ps(&s)
    fmt.Println(s)
}
like image 144
OneOfOne Avatar answered Oct 12 '22 21:10

OneOfOne