Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Close
- C
- tcp
- write
- range
- go언어
- windows
- json
- File
- Python
- Golang
- Linux
- c++
- GO 언어
- window
- bitcoin
- mutex
- 리뷰
- channel
- package
- http
- FOR
- Sync
- install
- 책
- 영화
- API
- Callback
- go
- JavaScript
Archives
- Today
- Total
Code Habit
Go ) interface 본문
인터페이스는 메서드 집합이다. 단 인터페이스는 메서드 자체를 구현하지는 않는다.
- type 인터페이스명 interface {}
인터페이스 정의 예제이다.
1
2
3
4
5
6
7
8
9
10
11
|
package main
import "fmt"
type hello interface { // 인터페이스 정의
}
func main() {
var h hello // 인터페이스 선언
fmt.Println(h) // nil: 빈 인터페이스이므로 nil이 출력됨
}
|
메서드를 가지는 인터페이스를 정의해 보자.
- type 인터페이스명 interface { 메서드 }
인터페이스 활용 예제이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package main
import "fmt"
type MyInt int // int 형을 MyInt로 정의
func(i MyInt) Print() { // MyInt에 Print메서드를 연결
fmt.Println(i)
}
type Rectangle struct { // 사각형 구조체 정의
width, height int
}
func (r Rectangle) Print() { // Rectangle에 Print 메서드를 연결
fmt.Println(r.width, r.height)
}
type Printer interface { // Print 메서드를 가지는 인터페이스 정의
Print()
}
func main() {
var i MyInt = 5
r := Rectangle{10, 20}
var p Printer // 인터페이스 선언
p = i // i를 인터페이스 p에 대입
p.Print() // 5: 인터페이스 p를 통하여 MyInt의 Print 메서드 호출
p = r // r을 인터페이스 p에 대입
p.Print() // 10 20 : 인터페이스 p를 통하여 Rectangle의 Print 메서드 호출
}
|
Printer 인터페이스 p에 MyInt 형 변수 i를 대입했다. 마찬가지로 다시 p에 Rectangle 인스턴스를 대입했다. 이렇게 전혀 다른 타입을 인터페이스에 대입할 수 있다. 즉 인터페이스는 자료형이든 구조체든 타입에 상관없이 메서드 집합만 같으면 동일한 타입으로 본다. 인터페이스의 메서드를 호출하면 인터페이스에 담긴 실제 타입의 메서드가 호출되므로 MyInt형 변수를 대입한 뒤 Print 함수를 호출하면 5가 출력되고, Rectangle 인스턴스를 대입하면 10과 20이 출력된다.
인터페이스를 선언하면서 초기화하려면 다음과 같이 :=를 사용하면 된다.
1
2
3
4
5
6
7
8
|
var i MyInt = 5
r := Rectangle{10, 20}
p1 := Printer(i) // 인터페이스를 선언하면서 i로 초기화
p1.Print() // 5
p2 := Printer(r) // 인터페이스를 선언하면서 r로 초기화
p2.Print() // 10 20
|
다음과 같이 배열(슬라이스) 형태로도 인터페이스를 초기화할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
|
var i MyInt = 5
r := Rectangle{10, 20}
pArr := []Printer{i, r} // 슬라이스 형태로 인터페이스 초기화
for index, _ := range pArr {
pArr[index].Print() // 슬라이스를 순회하면서 Print 메서드 호출
}
for _, value := range pArr {
value.Print() // 슬라이스를 순회하면서 Print 메서드
}
|
실행 결과
5
10 20
5
10 20
|