성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>Golang - 인터페이스 포인터가 의미 있을까요?</h1> <p> 그렇습니다. 정말 몰라서 질문하는 것입니다. ^^<br /> <br /> 설명을 위해, Go 언어에서 간단하게 인터페이스를 구현해 볼까요? ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > package main import "fmt" <span style='color: blue; font-weight: bold'>type Person interface { GetAge() int }</span> type Student struct { Age int } <span style='color: blue; font-weight: bold'>func (student Student) GetAge() int { return student.Age }</span> func main() { student := Student{ Age: 5 } <span style='color: blue; font-weight: bold'>person := student</span> <span style='color: blue; font-weight: bold'>fmt.Println(person.GetAge())</span> } </pre> <br /> C/C++에 익숙하신 분들은, 위의 경우 GetAge 함수가 값 복사가 된 Student 인스턴스가 넘어왔다는 것을 알 것입니다. 그래서, GetAge 함수에서 값을 변경해도 호출 측에서 넘겨준 인스턴스의 값을 변경할 수는 없습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > func (student Student) GetAge() int { <span style='color: blue; font-weight: bold'>student.Age = 10</span> return student.Age } func main() { student := Student{ Age: 5 } <span style='color: blue; font-weight: bold'>person := student</span> fmt.Println(person.GetAge()) // 출력 결과: 10 fmt.Println(student.Age) // 출력 결과: 5 } </pre> <br /> 만약, 호출 측의 인스턴스에 영향을 주고 싶다면 GetAge 함수 선언을 다음과 같이 포인터 형식으로 바꿔야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > func (<span style='color: blue; font-weight: bold'>student *Student</span>) GetAge() int { student.Age = 10 return student.Age } func main() { student := Student{ Age: 5 } <span style='color: blue; font-weight: bold'>person := &student</span> fmt.Println(person.GetAge()) // 출력 결과: 10 fmt.Println(student.Age) // 출력 결과: 10 } </pre> <br /> 그런데 위에서 좀 재미있는 부분이 있지 않나요? 즉, 인터페이스 측에 선언한 GetAge 함수의 signature와는 별도로 그 규약을 따르는 타입 측에서는 GetAge라는 함수를 2가지 유형으로 정의할 수 있다는 점입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // receiver를 값 형식으로 받는 함수로 정의해도 되고. func (<span style='color: blue; font-weight: bold'>student Student</span>) GetAge() int { return student.Age } // 포인터 형식을 받는 함수로 정의해도 되고. func (<span style='color: blue; font-weight: bold'>student *Student</span>) GetAge() int { return student.Age } </pre> <br /> 게다가 둘 중 하나만 가능합니다. 그렇지 않으면 다음과 같은 식으로 컴파일 오류가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > # command-line-arguments .\main.go:19:6: method redeclared: Student.GetAge method(Student) func() int method(*Student) func() int </pre> <br /> 어쩔 수 없습니다. 만약 저런 경우가 필요하다면 각각의 함수 이름을 달리해 만들어야 합니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 그런데, 이런 규칙이 인터페이스를 인자로 받아들이는 경우가 되면 약간 혼란이 옵니다. 가령, 다음과 같은 예제 코드에서,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > package main import "fmt" type Person interface { GetAge() int } type Student struct { Age int } <span style='color: blue; font-weight: bold'>type MyFunc func(person Person)</span> func (<span style='color: blue; font-weight: bold'>student Student</span>) GetAge() int { return student.Age } func main() { student := Student{ Age: 5 } <span style='color: blue; font-weight: bold'>func1 := func(person Person) { fmt.Println(person.GetAge()) } func1(student)</span> fmt.Println(student.Age) } </pre> <br /> 값 복사를 막기 위해 포인터 처리를 해야 한다면 어떻게 될까요? 이때 자칫 실수의 여지가 있는데요, 소스 코드가 복잡하다 보면 아래와 같은 식의 시도도 할 수 있다는 점입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > type MyFunc func(<span style='color: blue; font-weight: bold'>person *Person</span>) func (student Student) GetAge() int { return student.Age } func main() { student := Student{ Age: 5 } func1 <span style='color: blue; font-weight: bold'>:=</span> func(<span style='color: blue; font-weight: bold'>person Person</span>) { fmt.Println(person.GetAge()) } func1(student) fmt.Println(student.Age) } </pre> <br /> 무심코 ":=" 연산자를 사용했기 때문에 위의 코드는 컴파일 오류도 발생하지 않습니다. 왜냐하면 ":="로 하는 경우 기존 타입 정의가 없어도 Go 컴파일러가 추론으로 타입을 처리하기 때문에 위에서 MyFunc 타입과 독립적으로 "func1" 변수의 타입이 정의되기 때문입니다. 따라서, 원래 의도한 대로라면 다음과 같이 명시적으로 MyFunc와 func1을 연결해야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>type MyFunc func(person *Person)</span> func main() { student := Student{ Age: 5 } /* 컴파일 오류 .\main.go:23:8: cannot use func literal (type func(Person)) as type MyFunc in assignment */ <span style='color: blue; font-weight: bold'>var func1 MyFunc</span> func1 = func(<span style='color: blue; font-weight: bold'>person Person</span>) { fmt.Println(person.GetAge()) } /* 컴파일 오류 .\main.go:27:7: cannot use student (type Student) as type *Person in argument to func1: *Person is pointer to interface, not interface */ func1(student) fmt.Println(student.Age) } </pre> <br /> 이제는 컴파일 오류가 발생하는 것이 당연하지만, 그렇다고 양측의 타입을 일치시켜도 여전히 오류가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > func main() { student := Student{ Age: 5 } /* 이제는 타입 추론으로 변경 */ func1 <span style='color: blue; font-weight: bold'>:=</span> func(<span style='color: blue; font-weight: bold'>person *Person</span>) { /* 컴파일 오류 .\main.go:24:21: person.GetAge undefined (type *Person is pointer to interface, not interface) */ fmt.Println(person.GetAge()) } /* 컴파일 오류 .\main.go:27:7: cannot use student (type Student) as type *Person in argument to func1: *Person is pointer to interface, not interface */ func1(<span style='color: blue; font-weight: bold'>student</span>) /* 컴파일 오류 .\main.go:29:8: cannot use &student (type *Student) as type *Person in argument to func1: *Person is pointer to interface, not interface */ func1(<span style='color: blue; font-weight: bold'>&student</span>) fmt.Println(student.Age) } </pre> <br /> 위와 같은 경우에 대한 근본적인 원인은, Go 언어에서 인터페이스는 포인터 타입이 없다는 것입니다. 따라서, 위와 같은 경우 인터페이스가 아닌 구현 타입 측에서만 포인터 처리를 해 주면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > func (<span style='color: blue; font-weight: bold'>student *Student</span>) GetAge() int { <span style='color: blue; font-weight: bold'>student.Age = 10</span> return student.Age } func main() { student := Student{ Age: 5 } func1 := func(<span style='color: blue; font-weight: bold'>person Person</span>) { fmt.Println(person.GetAge()) // 출력 결과 10 } func1(&student) fmt.Println(student.Age) // 출력 결과 10 } </pre> <br /> 자칫 이전의 C/C++ 느낌으로 인터페이스를 포인터 처리하게 되면 "[Type] is pointer to interface, not interface"라는 오류에서 헤매게 될 것입니다. ^^;<br /> <br /> <hr style='width: 50%' /><br /> <br /> 이에 대한 자세한 설명을 다음의 문서에서 볼 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Interface values ; <a target='tab' href='https://tour.golang.org/methods/11'>https://tour.golang.org/methods/11</a> // An interface value holds a value of a specific underlying concrete type. </pre> <br /> 정리해 보면, interface 변수는 타입 정보를 보관한다는 것인데, 인터페이스 포인터 형식이라면 "그 타입 정보에 대한 포인터"가 되는데 그런 의미에서 딱히 유용한 형식으로 보이진 않습니다. 사실 interface 변수의 기본값은 nil이라는 점에서 그것 자체가 포인터와 닮아 있긴 합니다. 그러므로, 애당초 인터페이스 변수에 값을 담을 수도 있고, 참조를 담을 수도 있으므로 인터페이스 자체의 포인터를 선언할 필요가 없는 것입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > type Space interface { GetPosition() (x, y int) } type Point struct { X int Y int } func main() { pt := Point{5,10} <span style='color: blue; font-weight: bold'>var space1, space2 Space space1 = pt // 값도 담을 수 있고, space2 = &pt // 참조도 담을 수 있고</span> space1.GetPosition() space2.GetPosition() } </pre> <br /> 그런데, 여기서 또 재미있는 것은 인터페이스의 정의와는 무관하게 그것에 맞춰 구현하는 타입의 receiver가 어떤 메서드를 포함했느냐에 따라 위의 코드가 컴파일 오류가 발생할 수도 있다는 점입니다.<br /> <br /> 가령, 위의 예제에서 SetPosition만을 다음과 같이 추가하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > type Space interface { GetPosition() (x, y int) SetPosition(x, y int) } ...[생략]... func <span style='color: blue; font-weight: bold'>(pt *Point)</span> SetPosition(x, y int) { pt.X, pt.Y = x, y } </pre> <br /> 컴파일 시 이제는 다음과 같은 오류가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > func main() { pt := Point{5,10} var space1, space2 Space /* 컴파일 오류 .\main.go:46:9: cannot use pt (type Point) as type Space in assignment: Point does not implement Space (SetPosition method has pointer receiver) */ <span style='color: blue; font-weight: bold'>space1 = pt</span> space2 = &pt space1.GetPosition() space2.GetPosition() } </pre> <br /> 즉, SetPosition 메서드에 포인터 형의 receiver가 정의되었으므로 값으로는 더 이상 받을 수 없다는 것입니다. 따라서 이런 경우에는 무조건 "space2 = &pt"와 같이 포인터 값을 보관하는 것만 가능합니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 인터페이스와 관련해 또 하나 실수할 수 있는 여지를 하나 볼까요? ^^<br /> <br /> 가령, 처음에는 대상 타입의 포인터를 가리켜 다음과 같이 잘 사용하던 코드가 있다고 가정했을 때,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > type Student struct { Age int } type Company struct { <span style='color: blue; font-weight: bold'>Owner *Student</span> } func main() { student := Student{ Age: 5 } <span style='color: blue; font-weight: bold'>company := Company{&student}</span> fmt.Println(company.Owner.GetAge()) fmt.Println(student.Age) } </pre> <br /> 나중에 리팩터링을 하면서 Company의 Student를 인터페이스로 변경하는 일이 발생해 무심코 타입명만 변경해 버리면 다시 컴파일 오류에 시달리게 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>type Person interface</span> { GetAge() int } type Student struct { Age int } // ...[생략]... type Company struct { <span style='color: blue; font-weight: bold'>Owner *Person</span> } func main() { student := Student{ Age: 5 } /* 컴파일 오류 .\main.go:60:21: cannot use &student (type *Student) as type *Person in field value: *Person is pointer to interface, not interface */ company := Company{&student} /* 컴파일 오류 .\main.go:61:27: company.Owner.GetAge undefined (type *Person is pointer to interface, not interface) */ fmt.Println(company.Owner.GetAge()) fmt.Println(student.Age) } </pre> <br /> 명심하세요, 절대 인터페이스는 포인터 타입이 와서는 안 됩니다. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > type Company struct { <span style='color: blue; font-weight: bold'>Owner Person</span> } // 이하 정상 컴파일 </pre> <br /> 저럴 거면, 아예 인터페이스 타입의 필드를 정의하는 단계에서 불가능하게 처리를 했어야 하지 않을까요? 혹시, 이 글을 읽고 있는 분들 중에 인터페이스를 포인터 타입으로 선언해 사용한 좋은 사례가 있는지, 있다면 덧글 부탁드립니다. ^^<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1040
(왼쪽의 숫자를 입력해야 합니다.)