interface 와 Struct Embed 예제 > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

Go lang | interface 와 Struct Embed 예제

본문

[code]

package main


/**

* Api Interface

**/

type Api interface {

  save() (bool, error)

}


/**

* Work Structure

**/

type Work struct { }


func (w *Work) Test() {

  println("테스트!!!!")

}


/**

* ApiChild Structure

**/

type ApiChild struct {

  Work // Work Struct Embed

}


// Api interface 를 구현

func (a *ApiChild) save() (bool, error) {

  println("저장!")

  return true, nil

}


/**

* App Structure

**/

type App struct {

  api Api

}



func main() {

  app := new(App)

  app.api = new(ApiChild)

  app.api.save() // Api 를 구현한 save() 메소드 호출

  c := app.api.(*ApiChild) // Assertion 으로 Downcast

  c.Test() // Work 의 Method 를 사용할 수 있다.

}

[/code]

 

출력

[code]

저장!

테스트!!!!

[/code]

 

댓글 0개

등록된 댓글이 없습니다.

Menu