Skip to content

Instantly share code, notes, and snippets.

@Micrified
Last active March 10, 2024 18:26
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 Micrified/18f8762d6c6bf4f05b438748950ba4a1 to your computer and use it in GitHub Desktop.
Save Micrified/18f8762d6c6bf4f05b438748950ba4a1 to your computer and use it in GitHub Desktop.
Generic struct composition
package main
import "fmt"
import "encoding/json"
import "bytes"
type AuthPost [T any] struct {
UserID string `json:"userid"`
SID string `json:"sid"`
Data T `json:"data"`
}
type PostBlog struct {
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Body string `json:"body"`
}
func main() {
fmt.Println("Hello World!")
body := "Nature's first green is gold,\n" +
"Her hardest hue to hold.\n" +
"Her early leaf's a flower;\n" +
"But only so an hour.\n" +
"Then leaf subsides to leaf.\n" +
"So Eden sank to grief,\n" +
"So dawn goes down to day.\n" +
"Nothing gold can stay."
msg := AuthPost[PostBlog] {
UserID: "micrified",
SID: "a783-8kx8-229p-1kd8",
Data: PostBlog {
Title: "Nothing Gold Can Stay",
Subtitle: "By Robert Frost",
Body: body,
},
}
// Encode
buffer := bytes.Buffer{}
json.NewEncoder(&buffer).Encode(msg)
fmt.Println(buffer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment