A Tour to Go

The rule is that public functions, types, etc., should be upper case.

Variable

package main

import "fmt"

func main(){
  var msg string
  msg = "hello world"
  fmt.Println(msg)

 msg := "hello world"
  fmt.Println(msg)

  a, b:= 10, 15
}

基本データ型

package main
import "fmt"

func main(){
  a := 10
  b := 12.3
  c := "hoge"
  var d bool
  fmt.Printf("a: %d, b:%f, c:%s, d:%t\n", a, b, c, d)
}

const, iota: https://github.com/golang/go/wiki/Iota

package main
import "fmt"

func main(){
  // const name = "yoshida"
  // name = "tanaka"

  const (
    sun = iota
    mon
    tue
  )
  fmt.Println(sun, mon, tue)
}

pointer

package main
import "fmt"

func main(){
  a := 5
  var pa *int
  pa = &a // a address
  fmt.Println(pa)
  fmt.Println(*pa)
}

function

package main
import "fmt"

func hi(name string) string{
  msg := "hi!" + name
  return msg
}

func main(){
  fmt.Println(hi("tanaka"))
}

swap

package main
import "fmt"

func swap(a, b int)(int, int){
  return b, a
}

func main(){
  fmt.Println(swap(5, 2))
}

array

a := [...]int{1, 3, 5}
a := [5]int{1, 3, 5, 8, 9}
  s := a[2:4]
  fmt.Println(s)
  fmt.Println(len(s))
  fmt.Println(cap(s))
  s := []int{1, 3, 5}
  s = append(s, 8, 2, 10)
  t := make([]int, len(s))
  n := copy(t, s)

map

  m := make(map[string]int)
  m["tanaka"] = 200
  m["sato"] = 300
  fmt.Println(m)

if

score := 83
  if score > 80 {
    fmt.Println("great")
  } else {
    fmt.Println("soso")
  }

range

s := []int{2, 3, 8}
  for i, v := range s{
    fmt.Println(i, v)

構造体

type user struct {
  name string
  score int
}

func main(){
    u := new(user)
    u.name = "tanaka"
    fmt.Println(u)

}

go routine

package main
import (
  "fmt"
  "time"
  )

func task1(){
  time.Sleep(time.Second * 2)
  fmt.Println("task1 finished!")
}
func task2(){
  fmt.Println("task2 finished!")
}

func main(){
  go task1()
  go task2()

  time.Sleep(time.Second * 3)
}