assign a value to a pointer to a string in go

To assign a value to a pointer to a string in Go, first, we need to declare a pointer variable using the * before the variable name, and then assign the address of the string variable to the pointer variable using the & operator.

Here's an example:

main.go
package main

import "fmt"

func main() {
    var str string = "hello world"
    var ptr *string

    ptr = &str

    fmt.Println("Value of str:", str)
    fmt.Println("Value of ptr:", *ptr)
}
193 chars
14 lines

In the above example, we declared a string variable str and initialized it with the value "hello world". We also declared a pointer variable ptr of type *string.

Then, we assigned the address of str to ptr using the & operator.

Finally, we printed the value of str and the value pointed by ptr (which is the same as the value of str) using the * operator.

Output:

main.go
Value of str: hello world
Value of ptr: hello world
52 chars
3 lines

Note that when we want to access the value pointed by the pointer variable, we need to use the * operator before the variable name to dereference it.

related categories

gistlibby LogSnag