create a function that returns a pointer to an int in go

In Go, functions can return pointers to values of any data type, including pointers to integers. To create a function that returns a pointer to an integer, you can follow this example:

main.go
func returnIntPtr() *int {
    x := 5
    return &x
}
54 chars
5 lines

In the above code, the returnIntPtr function creates an integer variable x with a value of 5, and then returns a pointer to that variable using the & operator.

You can also pass the pointer to an integer to a function to modify its value:

main.go
func modifyIntPtr(x *int) {
    *x = 10
}

func main() {
    x := returnIntPtr()
    modifyIntPtr(x)
    fmt.Println(*x) // Output: 10
}
137 chars
10 lines

In the above code, the modifyIntPtr function takes a pointer to an integer as its argument, and modifies the value of the integer to 10 using the * operator. The main function calls returnIntPtr to get a pointer to an integer, then calls modifyIntPtr to change its value to 10, and finally prints the new value of the integer.

gistlibby LogSnag