Go 구조체&인터페이스
Go 구조체&인터페이스
구조체
C/C++ 프로그래밍 언어에서 구조화 된 데이터를 처리할 때 struct를 사용하는데 이를 구조체라고 한다.(출처:위치백과)
구조체 사용법
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
34
35
36
37
38
// 구조체 정의
type MyStruct struct{
myInt int
myString string
}
// 구조체 선언
var ms MyStruct
// pointer
var ms *MyStruct
ms := new(MyStruct)
//new로 메모리 할당하는 동시에 값을 초기화하지 못함
//다음과 같은 방법으로 유사하게 표현가능
func newMyStruct(myInt int,myString string) *MyStruct{
return &MyStruct{myInt,myString}
}
// 구조체를 넘겨줘서 구조체의 내용을 print하는 함수
func PrintStruct(ms *MyStruct){
fmt.Println(ms.myInt,ms.myString)
}
// 구조체에 함수를 연결하는 방법
// 포인터 형식으로 리시버를 선언하면 구조체의 변수를 변경하게 되면 원래 값에 영향을 줌
func (ms *MyStruct) MyPrint(){
fmt.Println(ms.myInt,ms.myString)
}
func main(){
ms := newMyStruct(1997,"JJ")
fmt.Println(ms) // &{1997 JJ}
PrintStruct(ms) //1997 JJ
ms.MyPrint()//1997 JJ
}
위처럼 Go에서는 구조체가 다른 언어에서 접했던 구조체와 큰 차이가 없는듯 하다. 다만 임베딩(Embedding)이라는 상속과 유사한 기능이 있다.
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
type Employee struct{
name string
}
func (doby *Employee) Speak(){
fmt.Println(doby.name, "is Free~")
}
// Is - a 관계
// 구조체의 함수나 변수 참조시 Dog.Employee.name || Dog.name으로 참조 가능함
type Dog struct{
Employee //Embeding
salary int
}
//Has - a 관계
// 구조체의 함수나 변수 참조시 Slave.e.name 과 같은 방식으로 참조
type Slave struct{
e Employee
salary int
}
type
func main(){
d := Dog{
Employee:Employee{name:"JJ"},
salary: 10,
}
s := Slave{
Employee:Employee{name:"me"},
salary: 0,
}
d.Speak() // JJ is Free~
s.e.Speak() // me is Free~
fmt.Println("My Salary is : ", d.salary) //10
}
인터페이스
인터페이스는 함수의 집합이다. 그리고 인터페이스에서는 함수를 구현하지 않는다.
``` go
```
This post is licensed under CC BY 4.0 by the author.