Cara Print Variabel Struct dan JSON di Golang
- Categories:
- golang
Salah satu cara debug saat membuat program adalah melakukan print atau menampilkan suatu variabel. Pada Golang, hal ini dapat dilakukan dengan dua cara, yaitu dengan Printf
dan json.Marshal
ditambah Println
.
package main
import (
"fmt"
"encoding/json"
)
type Project struct {
Id int `json:"project_id"`
Name string `json:"name"`
}
func main() {
myProject := Project{
Id: 1,
Name: "@kaklabs",
}
fmt.Printf("%+v\n", myProject)
yourProject := Project{
Id: 2,
Name: "KAK Labs",
}
res, _ := json.Marshal(yourProject)
fmt.Println(string(res))
}
Keluaran dari kode Go diatas adalah sebagai berikut.
{Id:1 Name:@kaklabs}
{"project_id":2,"name":"KAK Labs"}
Perbedaan dari kedua cara diatas adalah %+v
menampilkan field dari struct
sedangkan json.Marshal
menampilkan field dari JSON. Kode diatas dapat diakses melalui The Go Playground.
Recent Posts
C# DbContext ServiceLifeTime
my note about C Sharp ServiceLifeTime
PostgreSQL Index Usage Monitoring
Having too many unused or underused indexes on a table can slow down write and update operations in your PostgreSQL database, making it crucial to regularly identify and manage them for optimal performance.
KAK Labs Newsletter #6 - Staying Safe From Pegasus Spyware
Newsletter #6 - Pegasus, Ruby, PostgreSQL and networkQuality tool
Material Design - Paragraph Spacing
According to Google's Material Design, keep paragraph spacing in the range between .75x and 1.25x of the type size.
Amazon SDK for C# - S3 File Download Methods
Comparison between `TransferUtility.DownloadAsync`, `DownloadSingleFileAsync`, and `GetObjectAsync`.