Skip to content

Instantly share code, notes, and snippets.

@stnc
Last active September 6, 2023 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stnc/6a0a5267c4f0bfbbad53d70dba95f838 to your computer and use it in GitHub Desktop.
Save stnc/6a0a5267c4f0bfbbad53d70dba95f838 to your computer and use it in GitHub Desktop.
golang deep pointer example
package main
import (
"fmt"
)
func increment(ptr *int) {
*ptr = *ptr + 1
}
func main() {
val :=5
increment(&val)
fmt.Println("The incremented val is given below:")
fmt.Println(val)
}
//--------------------------------
package main
import (
"fmt"
)
// https://go.dev/play/p/TmrXMHKMjlt
// https://golangprojectstructure.com/pointer-variables-go-code-examples/
type Server struct {
name string
}
// setName if * pointer = ok
func (server *Server) setName(newName string) {
server.name = newName
}
type Client struct {
name string
}
// setName if not * pointer = not change
func (client Client) setName(newName string) {
client.name = newName
}
func main() {
fmt.Println("/////---------- example 1 only struct access")
server := Server{
name: "John",
}
fmt.Println(server.name)
fmt.Println("/////---------- example 2 --changed because pointer ")
serverPointer := Server{
name: "John",
}
fmt.Println(serverPointer.name)
serverPointer.setName("Jack") // changed
fmt.Println(serverPointer.name)
fmt.Println("/////---------- example 3 (client struct) not change because is not pointer ")
client := Client{
name: "John",
}
fmt.Println(client.name)
client.setName("Jack")
fmt.Println(client.name)
}
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int = 200
fmt.Printf("Before swap, value of a : %d\n", a)
fmt.Printf("Before swap, value of b : %d\n", b)
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b)
fmt.Printf("After swap, value of a : %d\n", a)
fmt.Printf("After swap, value of b : %d\n", b)
}
func swap(x *int, y *int) {
var temp int
temp = *x /* save the value at address x */
*x = *y /* put y into x */
*y = temp /* put temp into y */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment