Lenovo IdeaPad Slim 3 14ABR8 AMD Ryzen 5Lenovo IdeaPad Slim 3 14ABR8 82XL0004ID - ABYSS BLUE = LENOVO SLIM 3 82XL007CID R5-7530U/8GB/512GB/14.0/WIN11+OHS/ABYSS BLUE, Lenovo IdeaPad Slim 3 14ABR8 82XL0005ID - ARCTIC GREY = LENOVO SLIM 3 82XL007BID R5-7530U/8GB/512GB/14.0/WIN11+OHS/ARCTIC GREY Free Klik Disini ! |
Saat kita bekerja dalam environment project yang komplek, kita akan menemukan sebuah struct yang konstruktornya dipakai oleh banyak method.
Perhatikan contoh kode berikut ini:
package mainimport (
"encoding/json"
"fmt"
)type employee struct {
Name string `json:"name,omitempty"`
Address string `json:"address"`
}func main() {
dataEmployee := employee{
Name: "",
Address: "jalan raya kenari",
}byte, err := json.Marshal(dataEmployee)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(string(byte))
}
Result:
{"Address": "jalan raya kenari"}
Solusinya kita bisa menambahkan pointer pada tipe data dari object-key Name, menjadi seperti berikut:
Name *string `json:"name,omitempty"`
dnama := ""
dataEmployee := employee{
Name: &dnama,
Address: "jalan raya kenari",
}
Perhatikan kode program dibawah ini:
package mainimport (
"encoding/json"
"fmt"
)type employee struct {
Name *string `json:"name,omitempty"`
Address string `json:"address"`
}func main() {
dnama := ""
dataEmployee := employee{
Name: &dnama,
Address: "jalan raya kenari",
}byte, err := json.Marshal(dataEmployee)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(string(byte))
}
Result:
{"name":"","address":"jalan raya kenari"}