Files
2025-10-06 22:41:05 +08:00

77 lines
1.2 KiB
Go

package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
baseStruct()
innerStruct()
jsonStruct()
}
func baseStruct() {
type Product struct {
name, category string
price float64
}
kayak := Product{
name: "Kayak",
category: "Watersports",
price: 275,
}
fmt.Println(kayak.name, kayak.category, kayak.price)
kayak.price = 300
fmt.Println(kayak.name, kayak.category, kayak.price)
}
func innerStruct() {
type Product struct {
name, category string
price float64
}
type StockLevel struct {
Product
count int
}
stockItem := StockLevel{
Product: Product{
name: "Kayak",
category: "Watersports",
price: 275,
},
count: 100,
}
fmt.Println("Name:", stockItem.Product.name)
fmt.Println("Name:", stockItem.name)
fmt.Println("Count:", stockItem.count)
}
func jsonStruct() {
type Product struct {
name, category string
price float64
}
prod := Product{
name: "Kayak",
category: "Watersports",
price: 275,
}
var builder strings.Builder
err := json.NewEncoder(&builder).Encode(struct {
ProductName string
ProductPrice float64
}{
ProductName: prod.name,
ProductPrice: prod.price,
})
if err != nil {
return
}
fmt.Println(builder.String())
}