Go语言学习笔记(二)

6,变量

  1: var a int  // 默认a=0
  2: var b string  // b=""
  3: var c bool  // c=Fales
  4: var d int = 8
  5: var e string = "hello"
  6: 或者
  7: var{
  8: 	a int
  9: 	b string
 10: 	c bool
 11: 	d int = 8
 12: 	e string = "hello"
 13: }
 14: 格式化输出:
 15: fmt.Printf("a=%d b=%s c=%t d=%d e=%s\n", a, b, c, d, e)

7,常量

a.常量使用const修饰,代表永远只是只读的,不能修改。
b.语法:const identifiler[type]=value,其中type可以省略。

  1: const b string = "hello world"
  2: const b = "hello world"
  3: const Pi = 3.1414926
  4: const a = 9/3

或者

  1: const{
  2:     b1 string = "hello world"
  3:     b2 = "hello world"
  4:     Pi = 3.1414926
  5:     a = 9/3
  6: }

特殊写法:

  1: const{
  2: 	a int = 100
  3: 	b
  4: 	c int = 200
  5: 	d
  6: }
  7: a,b=100 c,d=100

iota每多一行就自增加一:

  1: const{
  2: 	a = iota
  3: 	b
  4: 	c
  5: }
  6: a=0 b=1 c=2

也可以这样写,效果和上面一样:

  1: const{
  2: 	a = iota
  3: 	b = iota
  4: 	c = iota
  5: }

另外一种用法:

  1: const{
  2: 	a1 = 1 << iota // iota默认等于0,a1左移0位,a1=1
  3:     a2 // a2左移1位,10(2)=2(10)
  4:     a3 // a3左移2位,100(2)=4(10)
  5: }
  6: a1=1 a2=2 a3=4

一个复杂点的例子:

  1: const{
  2: 	a = iota
  3: 	b = iota
  4: 	c = iota
  5: 	d = 8
  6: 	e
  7: 	f = iota
  8: 	g = iota
  9: }
 10: //输出:0,1,2,8,8,5,6

猜你喜欢

转载自www.cnblogs.com/haoqirui/p/10074458.html