【每日知识】go语言基本语法 2018-06-09

变量

变量的声明:
      var a int
      a = 10
      fmt.Println("a=", a)
      var b = 20
      fmt.Println("b =", b)
      c := 30//自动推导类型 
      fmt.Println("c=", c)

Println和Printf的区别

a := 12
b, c := 13, 14
fmt.Println(a, b, c) //有自动换行的功能
fmt.Printf("%d \n %d \n %d", a, b, c) //打印字符串"%d%d%d",同时用a,b,c的值替换%d //'\n'为换行的意思

多重赋值、函数调用和匿名变量

func main() {
    i, j := 11, 22
    i, j = j, i //多重赋值
    fmt.Printf("i=%d j=%d\n", i, j)
    var d, e, f int
    d, e, f = test() //函数的调用
    fmt.Printf("d=%d e=%d f=%d\n", d, e, f)
    var g int
    g, _ = i, j //匿名变量
    fmt.Println("g=", g)
    d, _, f = test()
    fmt.Println("d=", d, "f=", f)
}
func test() (a, b, c int) {
    return 1, 2, 3
}

常量和iota枚举

const a int = 10 //常量只能初始化,不可再赋值:a = 10
const b = 1.2 //自动推导类型不需要加“:”
fmt.Println("a=", a)
fmt.Printf("%T", b)//%T是打印类型的意思
const ( //专门给常量用的,从0开始累加
    a = iota
    b = iota
    c = iota
)
 fmt.Printf("a=%d b=%d c=%d\n", a, b, c)
 const d = iota //遇到const归零
 fmt.Println("d=", d)
 const (
     a1 = iota //可以省略后面的iota
     b1
     c1
     d1, e1, f1 = iota, iota, iota //同一行的值都是一样的
)
 fmt.Printf("a1=%d b1=%d c1=%d d1=%d e1=%d f1=%d", a1, b1, c1, d1, e1, f1)

bool类型

var a bool//初始值为false
fmt.Println("a0=", a)
a = true
fmt.Println("a=", a)
b := true
fmt.Println("b=", b)

浮点型

var a float32
a = 3.14
fmt.Println("a=", a)
b := 3.14 //自动推导的类型为float64
fmt.Printf("b type is %T", b)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容