go 언어의 구조체는 struct으로 사용할 수 있다. 


package main

import "fmt"


func main() {


  type Rectangle struct {

    X1 int

    Y1 int

    X2 int

    Y2 int

  }


  rect := Rectangle{1,1,5,5}

  fmt.Println(rect)


  rect.X1 = 10

  fmt.Println(rect)

}




결과


{1 1 5 5}

{10 1 5 5}





strcuct를 바깥에 두어도 동일하게 동작한다.


package main

import "fmt"


type Rectangle struct {

  X1 int

  Y1 int

  X2 int

  Y2 int

}


func main() {

  rect := Rectangle{1,1,5,5}

  fmt.Println(rect)


  rect.X1 = 10

  fmt.Println(rect)

}






struct를 포인터로 가르킬 수 있다. 



func main() {

  rect := Rectangle{1,1,5,5}

  fmt.Println(rect)


  rect.X1 = 10

  fmt.Println(rect)


  r := &rect

  r.Y1 = 1e2


  fmt.Println(r)

  fmt.Println(*r)

  fmt.Println(r==&rect)

}



결과는 다음과 같다.

{1 1 5 5}

{10 1 5 5}

&{10 100 5 5}

{10 100 5 5}

true





struct의 인스턴스를 생성할 때 p := new(구조체_이름) 또는 var p *구조체_이름 = new(구조체_이름)을 사용할 수 있다.


package main


type Rectangle struct {

  X1 int

  Y1 int

  X2 int

  Y2 int

}


func main() {

  p := new(Rectangle)

  p.X1 = 1

  println(p)

  println(p.X1)

  println(p.X2)

}




package main


type Rectangle struct {

  X1 int

  Y1 int

  X2 int

  Y2 int

}


func main() {

  var p *Rectangle = new(Rectangle)

  p.X1 = 1

  println(p)

  println(p.X1)

  println(p.X2)

}



이전 두 예제의 결과는 다음과 같다.


0xc42003ff58

1

0





구조체의 초기화를 제공하지는 않지만 앱단에서 구조체에 대한 초기화 함수를 생성할 수 있다. 


package main

import "fmt"

type Rectangle struct {
X1 int
Y1 int
X2 int
Y2 int
}

func main() {
rect := newRectangle()
fmt.Println(rect)
}

func newRectangle() *Rectangle {
r := Rectangle{}
r.X1 = -1
r.X2 = -1
r.Y1 = -1
r.Y2 = -1
return &r
}

결과는 다음과 같다. 


&{-1 -1 -1 -1}





메소드 예제이다. 

1번째 예제는 함수에서 구조체를 리턴하는 것이고,

2번째 예제는 함수에서 구조체를 참조하는 형태이다. 


package main

import "fmt"

type Rectangle struct {
X1 int
Y1 int
X2 int
Y2 int
}

func main() {
rect := newRectangle()
fmt.Println(rect)

// 1
newRect := rect.init0()
fmt.Println(newRect)

// 2
newRect.init1()
fmt.Println(newRect)

}

func newRectangle() *Rectangle {
r := Rectangle{}
r.X1 = -1
r.X2 = -1
r.Y1 = -1
r.Y2 = -1
return &r
}

func (r Rectangle) init0() Rectangle {
r.X1 = 0
r.X2 = 0
r.Y1 = 0
r.Y2 = 0

return r
}

func (r *Rectangle) init1() {
r.X1 = 1
r.X2 = 1
r.Y1 = 1
r.Y2 = 1
}


결과


&{-1 -1 -1 -1}

{0 0 0 0}

{1 1 1 1}



'golang' 카테고리의 다른 글

[golang] 매개 변수 받기  (0) 2017.09.08
[golang] 에러(error) 예제  (0) 2017.09.07
[golang] defer 예제  (0) 2017.09.07
[golang] interface(인터페이스) 예제  (0) 2017.09.06
[golang] 함수.클로져 예제  (0) 2017.09.06
Posted by '김용환'
,