Skip to main content

Pointer to struct

Updated 1 min readMarkdown
Part of series GopherLabs
Pointer to struct

Struct fields can be accessed through a struct pointer.

To access the field Xof a struct when we have the struct pointer pwe could write(*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.

func main() {
    z := xy{1, 2}
    p := &z
    p.X = 20
    fmt.Println(z)
}

Go Program

package main

import "fmt"

type xy struct {
    X int
    Y int
}

func main() {
    z := xy{1, 2}
    p := &z
    p.X = 20
    fmt.Println(z)
}

11 views

About the author

  • DevRel at StackGen | Formerly at Deepfence ,Tenable , Accurics | AWS Community Builder also Docker Community Award Winner at Dockercon2020 | CyberSecurity Innovator of Year 2023 award by Bsides Bangalore | Docker/HashiCorp Meetup Organiser Bangalore & Co-Author of Learn Lightweight Kubernetes with k3s (2019) , Packt Publication & also run Non Profit CloudNativeFolks / CloudSecCorner Community To Empower Free Education reach out me twitterhttps://twitter.com/sangamtwts or just follow on GitHub -> https://github.com/sangam14 for Valuable Resources

No comments yet. Be the first to comment.

More from this blog