Last active
April 12, 2022 04:19
-
-
Save AriffAzmi/19ba250a82d3ad51995e3df58e368718 to your computer and use it in GitHub Desktop.
Create array using struct in golang
This file contains 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" | |
"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