Last active
March 10, 2024 18:26
-
-
Save Micrified/18f8762d6c6bf4f05b438748950ba4a1 to your computer and use it in GitHub Desktop.
Generic struct composition
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 "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