Created
March 5, 2026 22:03
-
-
Save Grabber/4b3506f84de47c6accabeef4fd17c9cc to your computer and use it in GitHub Desktop.
golang experiments, structures with pointers and new operator from golang 1.26+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "errors" | |
| "fmt" | |
| ) | |
| // @NOTE: the core idea is to declare the struct values as a pointer. | |
| // .. if the key is required, ensure the value pointer isn't nil. | |
| type X struct { | |
| A *string `json:"a,omitempty"` | |
| B *int `json:"b,omitempty"` | |
| } | |
| func (x *X) Validate() error { | |
| if x.A == nil { // must have | |
| return errors.New("`a` can't be nil") | |
| } | |
| if *x.A == "" { | |
| return errors.New("`a` can't be empty") | |
| } | |
| if x.B != nil && *x.B == 0 { // may have | |
| return errors.New("`b` can't be zero") | |
| } | |
| return nil | |
| } | |
| func main() { | |
| // using the new operator (go 1.26+). | |
| // .. straightforward. | |
| x := X{ | |
| A: new("_a_"), | |
| B: new(1), | |
| } | |
| // taking the address of the first element from a slice. | |
| // .. non-anatomical. | |
| // x := X{ | |
| // A: &[]string{"_a_"}[0], | |
| // B: &[]int{1}[0], | |
| // } | |
| // declaring the variable and taking the address. | |
| // .. too verbose. | |
| // a := "_a_" | |
| // b := 1 | |
| // x := X{ | |
| // A: &a, | |
| // B: &b, | |
| // } | |
| fmt.Printf("x: %#v\n", x) | |
| fmt.Printf("x.A: %#v\n", *x.A) | |
| if x.B != nil { | |
| fmt.Printf("x.B: %#v\n", *x.B) | |
| } | |
| xJson, err := json.Marshal(x) | |
| if err != nil { | |
| panic(err) | |
| } | |
| fmt.Printf("xJson: %#v\n", string(xJson)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment