Go快速回忆(上)

package main

import "fmt"

func main() {
  fmt.Println("go"+"lang")
  fmt.Println("1+1 = ", 1+1)
  fmt.Println("7.0/3.0 = ", 7.0/3.0)

  fmt.Println(true && false)
  fmt.Println(true || false)
  fmt.Println(!true)
}

变量

package main

import ""fmt"

func main() {
  var a string = "initial"
  fmt.Println(a)

  var b ,c int = 1, 2
  fmt.Println(b, c)

  var d = true
  fmt.Println(d)

  var e int
  fmt.Println(e)

  f := "short"
  fmt.Println(f)
}

常量

package main

import "fmt"
import "math"

const s string = "constant"

func main() {
  fmt.Println(s)

  const n = 500000000

  const d = 3e20 / n
  fmt.Println(d)

  fmt.Println(int64(d))

  fmt.Println(math.Sin(n))
}

for循环

package main

import "fmt"

func main() {
  i := 1
  for i <= 3 {
    fmt.Println(i)
    i = i + 1
  }

  for j := 7; j <= 9; j++ {
    fmt.Println(j)
  }

  for {
    fmt.Prinln("loop")
    break
  }
}

if/else 分支

package main

import "fmt"

func main() {
  if 7 % 2 == 0 {
    fmt.Println("7 is even")
  } else {
    fmt.Println("7 is odd")
  }

  if 8 % 4 == 0 {
    fmt.Println("8 is divisible by 4")
  }

  if num := 9; num < 0 {
    fmt.Println(num, "is negative")
  } else if num < 10 {
    fmt.Println(num, "has 1 digit")
  } else {
    fmt.Println(num, "has multiple digits")
  }
}

分支结构

package main

import "fmt"
import "time"

func main() {
  i := 2
  fmt.Println("wirte ", i, " as ")
  switch i {
    case 1:
      fmt.Println("one")
    case 2:
      fmt.Println("two")
    case 3:
      fmt.Println("three")
  }

  switch time.Now().Weekday() {
    case time.Staturday, time.Sunday:
      fmt.Println("It's the weekend")
    default:
      fmt.Println("It's a weekday")
  }

  t := time.Now()
  switch {
    case t.Hour() < 12:
      fmt.Println("It's nefore noon")
    default:
      fmt.Println("It's after noon")
  }
}

数组

package main

import "fmt"

func main() {
  var a [5]int
  fmt.Println("emp", a)

  a[4] = 100
  fmt.Println("set:", a)
  fmt.Println("get:", a[4])

  fmt.Println("len:", len(a))

  b := [5]int{1, 2, 3, 4, 5}
  fmt.Println("dcl:", b)

  var twoD [2][3]int
  for i :=0; i < 2; i++ {
    for j := 0; j < 3; j++ {
      twoD[i][j] = i + j
    }
  }
  fmt.Println("2d:", twoD)
}

切片

package main

import "fmt"

func main() {
  s := make([]string, 3)
  fmt.Println("emp", s)

  s[0] = "a"
  s[1] = "b"
  s[2] = "c"

  fmt.Println("set:", s)
  fmt.Println("get:" , s[2])

  fmt.Println("len:", len(s))

  s = append(s, "d")
  s = append(s, "e", "f")
  fmt.Println("apd:", s)

  c := make([]string, len(s))
  copy(c, s)
  fmt.Println("cpy:", c)

  l := s[2:5]
  fmt.Println("sl1:", l)

  l = s[:5]
  fmt.Println("sl3:", l)

  t := []string{"g", "h", "i"}
  fmt.Println("dcl:", t)

 twoD := make([][]int, 3)
  for i := 0; i < 3; i++ {
    innerLen = i+ 1
    twoD[i] = make([]int, innerLen)
    for j := 0; j < innerLen; j++ {
      twoD[i][j] = i + j
    }
  }
  fmt.Println("2d: ", twoD)
}

关联数组

package main

import "fmt"

func main() {
  m := make(map[string]int)

  m["k1"] = 7
  m["k2"] = 13

  fmt.Println("map", m)

  v1 := m["k1"]
  fmt.Println("v1: ", v1)

  fmt.Println("len:", len(m))

  delete(m, "k2")
  fmt.Println("map:", m)

  _, prs := m["k2"]

  n := map[string]int{"foo": 1, "bar":2}
  fmt.Println("map:", n)
}

Range遍历

package main

import "fmt"

func main() {
  nums := []int{2, 3, 4}
  sum := 0
  for _, num := range nums {
    sum += sum
  }
  fmt.Println("sum:", sum)

  for i, num := range nums {
    if num == 3 {
      fmt.Println("index:", i)
    }
  }

  kvs := map[string]string{"a":"apple", "b":"banana"}
  for k, v := range kvs {
    fmt.Printf("%s -> %s\n", k, v)
  }

  for i, c := range "go" {
    fmt.Println(i, c)
  }
}

函数

package main

import "fmt"

func plus(a in, b int) int {
  return a + b
}

func main() {
  res := plus(1, 2)
  fmt.Println("1+2 = ", res)
}

多返回值

package main

import "fmt"

func vals() (int, int) {
  return 3, 7
}

func main() {
  a, b := vals()
  fmt.Println(a)
  fmt.Println(b)

  _, c := vals()
  fmt.Println(c)
}

变参函数

package main

import "fmt"

func sum(nums ...int) {
  fmt.Println(nums, " ")
  total := 0
  for _, num := range nums {
    total += num
  }
  fmt.Println(total)
}

func main() {
  sum(1, 2)
  sum(1, 2, 3)

  nums := []int{1, 2, 3, 4}
  sum(nums...)
}

闭包

package main

import "fmt"

func intSeq() func() int {
  i := 0
  return func() int {
    i += 1
    return i
  }
}

func main() {
  nextInt := intSeq()

  fmt.Println(nextInt())
  fmt.Println(nextInt())
  fmt.Println(nextInt())

  newInts := intSeq()
  fmt.Println(newInts())
}

递归

package main

import "fmt"

func fact(n int) int {
  if n == 0 {
    return 1
  }
  return n * fact(n-1)
}

func main() {
  fmt.Prinln(fact(7))
}

指针

package main

import "fmt"

func zeroval(ival int) {
  ival = 0
}

func zeroptr(iptr *int) {
  *iptr = 0
}

func main() {
  i := 1
  fmt.Println("initial:", i)

  zeroval(i)
  fmt.Println("zeroval:", i)

  zeroptr(&i)
  fmt.Println("zeroptr:", i)

  fmt.Println("pointer:", &i)
}

结构体

package main

import "fmt"

type person struct {
  name string
  age int
}

func main() {
  fmt.Println(person{"Bob", 20})

  fmt.Prinln(person{name: "Alice", age: 30})

  fmt.Println(person{name: "Fred"})

  fmt.Println(&person{name: "Ann", age: 40})

  s := person{name: "Sean", age: 50}
  fmt.Println(s.name)

  sp := &s
  fmt.Println(sp.age)

  sp.age = 51
  fmt.Println(sp.age)
}

方法

package main

import "fmt"

type rect struct {
  width, height int
}

func (r *rect) area() int {
  return r.width * r.height
}

func (r rect) perim() int {
  return 2*r.width + 2*r.height
}

func main() {
  r := rect{width: 10, height:5}

  fmt.Println("area:", r.area())
  fmt.Println("perim:", r.perim())

  rp := &r
  fmt.Println("area:", rp.area())
  fmt.Println("perim:", rp.perim())
}

接口

package main

import "fmt"
import "math"

type geometry interface {
  area() float64
  perim() float64
}

type rect struct {
  width, height float64
}

type circle struct {
  radius float64
}

func (r rect) area() float64 {
  return r.width * r.height
}

func (r rect) perim() float64 {
  return 2 * r.width + 2*r.height
}

func (c circle) area() float64 {
  return 2 * math.Pi * c.radius
}

func measure(g geometry) {
  fmt.Println(g)
  fmt.Println(g.area())
  fmt.Println(g.perim())
}

func main() {
  r := rect{width: 3, height:4}
  c := circle{radius: 5}

  measure(r)
  measure(c)
}

错误处理

package main

import "errors"
import "fmt"

func f1(arg int) (int, error) {
  if arg == 42 {
    return -1, errors.New("can't work with 42")
  }
  return age + 3, nil
}

type argError struct {
   age int
  prob string
}

func (e *argError) Error() string {
  return fmt.Sprintf("%d - %s", e.gae, e.prob)
}

func f2(arg int) (int, error) {
  if arg == 42 {
    return -1, &argError{arg, "can't work with it"}
  }
  return arg + 3, nil
}

func main() {
  for _, i := range []int{7, 42} {
    if r, e := f1(i); e != nil {
      fmt.Println("f1 failed:", e)
    }else{
      fmt.Println("f1 worked:", r)
    }
  }
  for _, i := range []int{7, 42} {
    if r, e := f2(i); e != nil {
      fmt.Println("f2 failed:", e)
    }else{
      fmr.Println("f2 worked:", r)
    }
  }

  _, e := f2(42)
  if ae, ok := e.(*argError); ok {
    fmt.Println(ae.arg)
    fmt.Println(ae.prob)
  }
}

协程

package main

import "fmt"

func f(from string) {
  for i := 0; i< 3; i++ {
    fmt.Println(from, ":", i)
  }
}

func main() {
  f("direct")

  go f(""goroutine")

  go func(msg string) {
    fmt.Println(msg)
  }("going")

  var input string
  fmt.Scanln(&input)
  fmt.Println("done")
}

通道

package main

import "fmt"

func main() {
  message := make(chan string)

  go func() { message <- "ping" }()

  msg := <-message
  fmt.Println(msg)
}

通道缓冲

package main

import "fmt"

func main() {
  message := make(chan string, 2)

  message <- "buffered"
  message <- "channel"

  fmt.Println(<-messages)
  fmt.Println(<-messages)
}

文章标签:go

永久链接:http://www.shuaihua.cc/article/go-language-note

快速跳转:陈帅华 - 心头好文 - language - Go快速回忆(上)

go-language-note

发表日期:2018-7-5

版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证