1. Package, variables and functions.

What is

  • Statically typed
  • Compiled language
  • Concurrency mechanisms

What is not

  • Object oriented

Basisc

Package

  • 관습적으로 import path의 마지막 element을 패키지 명으로 한다.
package "math/rand"

rand.Intn(10)
  • example path = math/rand
$ls /go/1.13.4/libexec/src/math/rand
  example_test.go
  exp.go
  gen_cooked.go
  normal.go
  race_test.go
  rand.go
  rand_test.go
  regress_test.go
  rng.go
  zipf.go
$cat rand.go
package rand
...
$cat exp.go
package rand
...

Import

  • 코드 그룹을 임포트한다.
import "fmt"
import (
    "fmt"
    "math"
)

Exported names

  • 만약 대문자로 이름이 시작하면 이름이 패키지 외부로 노출된다.

const (
    Pi  = 3.14.. 노출됨.
    pi  = 노출안됨.
)

Functions - input

  • input zero or more argument
func add(x int, y int) int {
    return x + y
}

Functions - output

  • 2개 이상의 output 리턴가능
func swap(x, y string) (string, string) {
    return  (x, y)
}

Named return values

  • 리턴값에 이름을 줄 수 있음.
func split(sum int) (x, y int) {
    x = sum
    y = sum / 2
    return
}

Variabls

var a, b bool = true, false

짧은 변수 선언

  • 함수 안에서만 사용가능
func main() {
    // var a = 1
    a := 1
    ...
}

기본 타입

  • 특별한 이유가 없는 이상 int 사용 권장 (32 컴터에서 32, 64에서 64)
  • float64 를 많이 사용 하는듯.
bool

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32
     // represents a Unicode code point

float32 float64

complex64 complex128

기본값

  • 명시적으로 값이 선언되어 있지 않으면 기본값이 초기값으로 자동 할당됨.
  • 숫자값 = 0
  • booltype = false
  • string = ""

타입변환

  • 묵시적 타입 변환 없음. 명시적으로 해야함.
var i int = 42
var f float64 = float64(i)

타입 추측

  • :=, var 를 할때 타입 선언이 없으면 할당된 값으로 추측.
i := 42           // int
f := 3.142        // float64
g := 0.867 + 0.5i // complex128

상수

  • := 로 선언 될 수 없음
const Pi = 3.14

숫자 상수

  • 숫자 상수는 매우 높은 정확도를 가지고 있음
  • 상수에 타입이 없으면 사용하는 곳에 맞춰 자동 형변환을 해줌.