6. 구조체(Structs)

: struct 는 필드(데이터)들의 조합이다. (그리고 type 선언으로 struct의 이름을 지정할 수 있다.)

type Vertex struct {
    X int
    Y int
}

func main() {
    fmt.Println(Vertex{1, 2})
}

6.1. 구조체 필드

: 구조체에 속한 필드는 <구조체명>.<필드명>으로 접근이 가능하다.

type Vertex struct {
    X int
    Y int
}

func main() {
    v := Vertex{1, 2}
    v.X = 4
    fmt.Println(v.X)
}

6.2. 구조체 리터널 (Struct Literals)

: 구조체 리터럴은 필드와 값을 나열해서 구조체를 새로 할당하는 방법이다. 원하는 필드를 {Name: value} 구문을 통해 할당할 수 있다. (필드의 순서는 상관 없다.) 특별한 접두어 & 를 사용하면 구조체 리터럴에 대한 포인터를 생성할 수 있다.

type Vertex struct {
    X, Y int
}

var (
    p = Vertex{1, 2} // has type Vertex
    q = &Vertex{1, 3} // has type *Vertex
    r = Vertex{X: 1} // Y:0 is implicit
    s = Vertex{} // X:0 and Y:0
)

func main() {
    fmt.Println(p, q, r, s)
}

6.3 new 함수

: new(T) 는 모든 필드가 0(zero value) 이 할당된 T 타입의 포인터를 반환한다. ( zero value 는 숫자 타입에서는 0 , 참조 타입에서는 nil 을 뜻한다. )

var t *T = new(T)

or

t := new(T)

위의 변수 t는 T에서 반환된 포인터를 가진다.

type Vertex struct {
    X, Y int
}

func main() {
    v := new(Vertex)
    fmt.Println(v)
    v.X, v.Y = 11, 9
    fmt.Println(v)
}

results matching ""

    No results matching ""