5.studying golang
- 사용자 정의 type
type arrayFlags []string
- type의 별칭을 선언하여 코드 가독성을 높이고 의미있게 사용하기 위함
- 변수 선언
var <변수이름> <변수 타입>
var flags arrayFlags
- method 정의
- method는 특정 type(특히 구조체)에 연결된 함수를 의미.
- value receiver : type의 값을 복사하여 method로 복사함 - 실제 값 변경 불가 (위의 예시)
func (method receiver) <method 이름()> <method 반환 type>
func (i *arrayFlags) String() string
- pointer receiver : type의 pointer를 method로 전달함 - 실제 값 변경 가능 (아래 예시)
func (i *arrayFlags) Set(value string) error
func (method receiver) <method 이름(매개변수, 매개변수 type)> <method 반환 type>
- method receiver
- method가 어떤 type에 속해 있는지를 나타내는 instance(위에서는 i가 instance)
- 이를 이용하면 특정 type에 method를 연결할 수 있고, 이를 통해 type 값들에 대해 method를 호출함.
- method를 정의할 때 함수 이름 앞 괄호 안에 작성됨.
- Channel
- goroutine 간의 통신을 위해 사용되는 데이터 구조
- make 함수를 사용하여 생성됨
<channel 이름> := make(chan <channel type>)
ready := make(chan bool)
- goroutine?
- go 언어에서 제공하는 경량 스레드(OS 수준에 비해 더 적은 리소스를 사용하여 빠르고 가벼운 실행단위)
- channel과 함께 사용되어 goroutine 간의 통신과 동기화를 쉽게할 수 있음
- main에서 프로그램 진입 후 차례대로 함수가 실행되는데, 각 함수는 별도의 goroutine에서 실행됨 (서로다른 창에서 실행된다고 생각하면 쉬움)
- flag package
- 다양한 type의 변수를 flag를 정의하여 command line에서 입력된 구문을 flag 값으로 설정함.
flag.<변수 tyupe>(string이름, defalut값, 설명문)
flag.Int(name string, defaultValue int, usage string)
go run main.go -intFlag=5678 -strFlag="hello" -boolFlag=true
에서-intFlag=5678
와 같은 값-
intFlag: 5678 strFlag: hello boolFlag: true
- function vs method
func functionName(변수이름 변수type) (반환값 반환type) {함수본문}
func (method receiver) <method 이름(매개변수, 매개변수 type)> <method 반환 type>
- 이름 앞에 (method receiver) 유무로 구분!
- 구조체의 field
- 구조체는 다양한 field로 이루어진다.
- 대표 library “context”
- 작업 간의 실행 시간을 제어(자동 타임아웃), 취소 신호를 전달해 특정 작업을 취소함, 요청 범위에 대한 값을 저장
- 동시성 프로그래밍에서 goroutine을 제어하고 조정하는 데 사용
- interface
- 여러 개의 method를 묶는 단위
- type error
- 오류 메세지를 문자열로 반환됨.