Instantiation using :=
Similarly, we can use :=
to instantiate a structure:
package main
import "fmt"
type Store struct {
productName string
productType string
price int
}
func main() {
lan3 := Store{}
lan3.productType = "Fresh Food"
lan3.productName = "Taiwanese Meatballs"
lan3.price = 20
fmt.Printf("lan3:\n\t%s\n\t%s\n\t%d\n",
lan3.productType, lan3.productName, lan3.price)
}
The result is as follows:
lan3:
Fresh Food
Taiwanese Meatballs
20
We can write initialization and assignment together, like this:
package main
import "fmt"
type Store struct {
productName string
productType string
price int
}
func main() {
lan3 := Store{
productType: "Fresh Food",
productName: "Taiwanese Meatballs",
price: 4,
}
fmt.Printf("lan3:\n\t%s\n\t%s\n\t%d\n",
lan3.productType, lan3.productName, lan3.price)
}
When we need to assign values to all fields of a structure, we can write values in the order they are defined in the structure.
For example, we rewrite the lan3
instance as follows:
lan3 := Store{
"Fresh Food",
"Taiwanese Meatballs",
4,
}
Note: This syntax is only suitable for cases where values are assigned to all fields.