create a pointer to a string in go

To create a pointer to a string in Go, you first need to declare a string variable and then take a reference to it using the & operator.

Here's an example:

main.go
package main

import "fmt"

func main() {
    var str string = "Hello, Gophers!"
    var ptrToStr *string = &str

    fmt.Println("Value of str:", str)
    fmt.Println("Address of str:", &str)
    fmt.Println("Value of ptrToStr:", ptrToStr)
    fmt.Println("Value pointed by ptrToStr:", *ptrToStr)
}
300 chars
14 lines

In this example, we create a variable str of type string and assign it the value "Hello, Gophers!". We then create a pointer variable ptrToStr of type *string and initialize it with the address of str using the & operator.

We can then print the value of str, the address of str, the value of ptrToStr, and the value that ptrToStr points to using the * operator.

Output:

main.go
Value of str: Hello, Gophers!
Address of str: 0x20818a220
Value of ptrToStr: 0x20818a220
Value pointed by ptrToStr: Hello, Gophers!
132 chars
5 lines

gistlibby LogSnag