:= 연산자를 사용한 인스턴스화
마찬가지로, :=를 사용하여 구조체를 인스턴스화할 수 있습니다.
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)
}
프로그램을 실행합니다.
go run struct.go
결과는 다음과 같습니다.
lan3:
Fresh Food
Taiwanese Meatballs
20
**초기화 (initialization)**와 **할당 (assignment)**을 함께 작성할 수 있습니다. 다음과 같이 말이죠.
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)
}
프로그램을 실행합니다.
go run struct.go
결과는 다음과 같습니다.
lan3:
Fresh Food
Taiwanese Meatballs
4
구조체의 모든 필드에 값을 할당해야 하는 경우, 구조체에 정의된 순서대로 값을 작성할 수 있습니다.
예를 들어, lan3 인스턴스를 다음과 같이 다시 작성합니다.
lan3 := Store{
"Fresh Food",
"Taiwanese Meatballs",
4,
}
참고: 이 구문은 모든 필드에 값을 할당하는 경우에만 적합합니다.