Skip to content

Instantly share code, notes, and snippets.

@AriffAzmi
Last active April 12, 2022 04:19
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 AriffAzmi/19ba250a82d3ad51995e3df58e368718 to your computer and use it in GitHub Desktop.
Save AriffAzmi/19ba250a82d3ad51995e3df58e368718 to your computer and use it in GitHub Desktop.
Create array using struct in golang
package main
import (
"encoding/json"
"fmt"
)
type Users struct {
Fullname string `json:fullname`
Phone int `json:phone`
Cars []Cars `json:cars`
}
type Cars struct {
Model string `json:model`
Brand string `json:brand`
PlateNo string `json:plate_no`
}
func main() {
var user Users
user.Fullname = "Abu"
user.Phone = 60123456789
user.Cars = append(user.Cars, Cars{
Model: "GTR",
Brand: "Nissan",
PlateNo: "ARP 1234",
})
user.Cars = append(user.Cars, Cars{
Model: "Skyline",
Brand: "Nissan",
PlateNo: "ARP 1233",
})
b, err := json.Marshal(user)
if err != nil {
fmt.Println("Unable to convert the struct to a JSON string")
}
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment