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?
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.).
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.
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.
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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With