이 글은 골든래빗 《Tucker의 Go 언어 프로그래밍》의 13장 써머리입니다.
type 타입명 struct {
필드명 타입
필드명 타입
...
}
type Student struct {
Name string
Class int
No int
Score float64
}
.
을 사용하면 된다.var a Student
a.Name = "Coen"
a.Class = 1
a.No = 10
a.Score = 100.0
초깃값 생략
, 모든 필드 초기화
, 일부 필드 초기화
방법이 있다.var a Student
fmt.Println(a.Name) //""
fmt.Println(a.Class) //0
fmt.Println(a.No) //0
fmt.Println(a.Score) //0.0
var a Student{"Coen", 1, 10, 100.0}
fmt.Println(a.Name) //"Coen"
fmt.Println(a.Class) //1
fmt.Println(a.No) //10
fmt.Println(a.Score) //100.0
필드명: 필드값
형식으로 초기화한다. 나머지 필드값은 기본값이 할당된다.var a Student{Name: "Coen", Score: 100.0}
fmt.Println(a.Name) //"Coen"
fmt.Println(a.Class) //0
fmt.Println(a.No) //0
fmt.Println(a.Score) //100.0
type User struct {
Name string
ID string
Age int
}
type VIPUser struct {
UserInfo User
VIPLevel int
Price int
}
func main() {
user := User{"Coen", "coen90", 34}
vip := VIPUser{user, 1, 1000}
fmt.Println(vip.UserInfo.Name) //"Coen"
fmt.Println(vip.VIPLevel) //1
}
type User struct {
Name string
ID string
Age int
}
type VIPUser struct {
User
VIPLevel int
Price int
}
func main() {
user := User{"Coen", "coen90", 34}
vip := VIPUser{user, 1, 1000}
fmt.Println(vip.Name) //"Coen"
fmt.Println(vip.VIPLevel) //1
}
type User struct {
Name string
ID string
Age int
Level int
}
type VIPUser struct {
User
VIPLevel int
Price int
Level int
}
func main() {
user := User{"Coen", "coen90", 34, 1111}
vip := VIPUser{user, 1, 1000, 9999}
fmt.Println(vip.Level) //9999
fmt.Println(vip.User.Level) //1111
}
type User struct {
Age int //8byte
Score int //8byte
}
var user User //16byte
type User struct {
Age int
Score int
}
user := User{20, 5}
user2 := user
type User struct {
Age int32 //4byte
Score float64 //8byte
}
var user User
t.Log(unsafe.Sizeof(user.Age)) //4
t.Log(unsafe.Sizeof(user.Score)) //8
t.Log(unsafe.Sizeof(user)) //16?!
Memory Padding
이라고 한다.type User struct {
A int //8byte
B int8 //1byte
C int //8byte
D int8 //1byte
E int //8byte
}
var user User
t.Log(unsafe.Sizeof(user)) //40
type User2 struct {
B int8 //1byte
D int8 //1byte
A int //8byte
C int //8byte
E int //8byte
}
var user2 User2
t.Log(unsafe.Sizeof(user2)) //32
type User struct {
Name string `json:"user_name"`
Age int `json:"user_age"`
}
user := User{"Coen", 34}
indent, err := json.MarshalIndent(user, "", " ")
if err != nil {
t.Fatal(err)
}
t.Log(string(indent))
{
"user_name": "Coen",
"user_age": 34
}
type User struct {
Name string `json:"user_name"`
Age int `json:"user_age"`
}
jsonString := "{\"user_name\":\"Coen\",\"user_age\":34}"
var user User
err := json.Unmarshal([]byte(jsonString), &user)
if err != nil {
t.Fatal(err)
}
t.Log(user) //{Coen 34}
type User struct {
Name string `json:"user_name"`
Age int `json:"user_age"`
}
user := User{"Coen", 34}
tsReflect := reflect.TypeOf(user)
name, _ := tsReflect.FieldByName("Name")
get := name.Tag.Get("json")
t.Log(get) //user_name