Go语言入门——基础语法 | 青训营笔记

55 阅读2分钟

这是我参与「第五届青训营 」笔记创作活动的第1天

1.1 go语言特点

  • 高性能,高并发 [Go 极其地快。其性能与 Java 或 C++相似]
  • 语法简单,学习曲线平缓
  • 丰富的标准库
  • 完善的工具链
  • 静态链接
  • 快速编译
  • 跨平台
  • 垃圾回收

1.2 打印Hello World

package main//程序入口

import (
   "fmt"//打印包
)

func main() {
   fmt.Println("hello world")
}

1.3 定义变量

第一种,指定变量类型,如果没有初始化,则变量默认为零值

第二种,根据值自行判定变量类型。

package main

import (
   "fmt"
   "math"
)

func main() {

   var a = "initial"

   var b, c int = 1, 2

   var d = true

   var e float64

   f := float32(e)

   g := a + "foo"
   fmt.Println(a, b, c, d, e, f) // initial 1 2 true 0 0
   fmt.Println(g)                // initialapple

   const s string = "constant"
   const h = 500000000
   const i = 3e20 / h
   fmt.Println(s, h, i, math.Sin(h), math.Sin(i))
}

1.4 if语句

package main

import "fmt"

func main() {

   if 7%2 == 0 { //go语言中不包含(),同时必须有大括号 不能写在同一行
      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")
   }
}

1.5 switch

switch 语句用于执行不同动作

switch 语句执行的过程从上至下,不需要再加 break。

switch 匹配成功后就不会执行其他 case

package main

import (
   "fmt"
   "time"
)

func main() {

   a := 2
   switch a {
   case 1:
      fmt.Println("one")
   case 2:
      fmt.Println("two")
   case 3:
      fmt.Println("three")
   case 4, 5:
      fmt.Println("four or five")
   default:
      fmt.Println("other")
   }

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

1.6 循环语句

package main

import "fmt"

func main() {

   i := 1
   for {//如果循环中条件语句永远不为 false 则会进行无限循环,我们可以通过 for 循环语句中只设置一个条件表达式来执行无限循环
      fmt.Println("loop")
      break
   }
   for j := 7; j < 9; j++ {//省略()
      fmt.Println(j)
   }

   for n := 0; n < 5; n++ {
      if n%2 == 0 {
         continue //继续执行下个循环
      }
      fmt.Println(n)
   }
   for i <= 3 {
      fmt.Println(i)
      i = i + 1
   }
}

1.7 切片

package main

import "fmt"

func main() {

   s := make([]string, 3)//make()  函数来创建切片
   s[0] = "a"
   s[1] = "b"
   s[2] = "c"
   fmt.Println("get:", s[2])   // c
   fmt.Println("len:", len(s)) // 3

   s = append(s, "d")
   s = append(s, "e", "f")
   fmt.Println(s) // [a b c d e f]

   c := make([]string, len(s))
   copy(c, s)
   fmt.Println(c) // [a b c d e f]

   fmt.Println(s[2:5]) // [c d e]
   fmt.Println(s[:5])  // [a b c d e]
   fmt.Println(s[2:])  // [c d e f]

   good := []string{"g", "o", "o", "d"}
   fmt.Println(good) // [g o o d]
}