Backend with Golang

Effective Go - Part 2

아직개구리 2023. 8. 10. 20:51

Initialization 

  • Init function : 각각의 source file에서 its own init function을 정의할 수 있다. 여러개 정의할 수도 있다. init 초기화 단계에서 마지막에 되는 단계라고 할 수 있다. init 함수는 모든 variable declaration이 끝난 뒤에 불리게 되며, imported packages가 모두 initialized되었을 때만 불린다. 선언의 형태로 표현할 수 없는 것들을 초기화 하는 것 이외에도, 실제 프로그램의 실행전에 상태를 검증하고 올바르게 복구하는데 자주 사용된다. 
  • Go 프로그램은 항상 main 함수로 시작된다. main package가 다른 패키지를 import 하고 있으면 import된 각각의 packages를 먼저 불러온다.  

Methods

  • Pointers vs Values: 메서드는 포인터와 인터페이스를 제외한 모든 Named Type 에 대해서 정의가 가능하다.
    • 중요한 부분:  As we saw with ByteSize, methods can be defined for any named type (except a pointer or an interface); the receiver does not have to be a struct. -> 모든 named type은 되지만, type NewInt *int 와 같이 pointer라면, NewInt에 대한 method를 정의할 수 없다는 것을 의미한다. 
    • 규칙이 하나 있는데, value methods는 pointer와 value 둘다에서 불릴 수 있지만, pointer method는 pointer에서만 불릴 수 있다. pointer method는 receiver를 수정할 수 있기 때문에, 값에 대해서 포인터 메서드를 호출하면 메서드가 값의 복사본을 숮신해서 수정사항이 버려지기 때문에 이러한 실수를 허용하지 않기 위해 생긴 규칙이다. 
    • value가 addressable할 때, compiler단에서 b.Write (write가 포인터 메서드)를 (&b).write()로 해서 실행한다. 

 

Questions

  • Named Type이란 ? 
    • 자료형에 새로 이름을 붙일 수 있고, 이런 자료형을 Named Type이라고 한다. 
      • type rune int32 
      • 같은 타입을 name을 다르게 붙인다고 했을 때, named type두개는 다른 타입으로 나온다. 비교나 반환을 할 때 해당 타입으로 변환을 해주는 과정을 거쳐야한다. 
  • 여기서 addressable하다는 것의 정의가 뭘까? 

 

 

Chris's Wiki :: blog/programming/GoAddressableValues

One of the tricky concepts in Go is 'addressable values', which show up in various places in the Go specification. To understand them better, let's pull all of the scattered references to them together in one place. The best place to start is with the spec

utcc.utoronto.ca