떤뚜 2019. 5. 9. 14:48

우선 interface는 method를 가지고 있고 해당 interface를 구현하려면 원하는 type에 해당 method들만 구현시켜 주면 된다.

type Handler interface {
	ServeHTTP(ResponseWriter, * Request)
}

를 구현하려면 

type testHandler struct {
} 

func (h *testHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}

와 같이 해주면 된다.

 

여기서 한가지 의문이 들었다.

type fake interface {
	ServeHTTP(ResponseWriter, * Request)
}

위 Handler interface와 똑같이 생긴 interface가 있다면 위 testHandler는 어디에 속하는 거지..?

......

답 은 속한다 라는 말 자체가 잘 못되었다는 거였다.

 

//interface
type i_test_1 interface {
	m_test_1()
}

type i_test_2 interface {
	m_test_l()
}

위의 두 interface는 같은 모양이지만 type명이 다르다.

interface의 기본 사용법대로라면 m_test_1()을 구현하면 두 interface모두에 해당이 되어버린다.

//struct
type s_test_1 struct {
	i_test_1
}

func (s *s_test_1) m_test_1() {
}

type s_test_2 struct {
	i_test_2
}

func (s *s_test_2) m_test_1() {
}

func f_test(i i_test_1) {
	println("interface!!!")
}

func main() {
	f_test(new(s_test_1))
	f_test(new(s_test_2))
}

// $ go run begin.go 
// interface!!! 
// interface!!!

위 코드처럼 interface 1번을 전달 받기로 한 function에 interface 1, 2를 바라보는 struct 두개를 각각 집어 넣어 보았다.

둘 다 잘 돌아간다.

 

goland의 interface는 어딘가에 속하는 개념이 아니다.

구현이 되었다면 그 interface로 사용할 수 있다.

 

예시로 하나의 struct에 두가지 interface의 method를 모두 구현한 뒤 각각의 interface를 변수로 받는 function에 넣어 보기로 했다.

 

func main() {
	f_test(new(s_test_1))
	f_test2(new(s_test_1))
}

//interface
type i_test_1 interface {
	m_test_1()
}

type i_test_2 interface {
	m_test_2()
}

//function
func f_test(i i_test_1) {
	println("interface!!!")
}

func f_test2(i i_test_2) {
	println("interface!!!")
}

//struct
type s_test_1 struct {
	i_test_1
}

func (s *s_test_1) m_test_1() {}
func (s *s_test_1) m_test_2() {}


// $ go run begin.go 
// interface!!! 
// interface!!!

잘 된다.

 

좋은 글 발견

https://opentutorials.org/module/2495/14142