go 学习笔记,2 --变量、常量、iota、数组

参考网址:https://gobyexample.com

变量

Go中使用全新的关键字var来声明变量。var我们并不陌生,在Javascript 和C#中均有出现。不同的是Go和C#中变量属于强类型,在声明变量后就不允许改变其数据类型。记住,Go属于强数据类型

声明及初始化

var a int //声明一个int类型的变量
 
var b struct { //声明一个结构体
 
  i string
 
}
 
var c = 1 //声明变量的同时赋值,编译器自动推导其数据类型
 
d := 1 //这种方式,含义同上,不书写类型,编译时会根据value自动推导类型进行匹配
 
var e int = 2 //声明变量的同时赋值
 
var { //批量声明变量,简洁
  f int
  g string
}

 值得注意的一点,赋值时如果要确定你想要的类型,在Go中是不支持隐式转换的。如果是定义个float64类型的变量,请写为

//前提:需要定义一个float类型的变量时:
//正确写法 
v1 := 3.0 
//错误写法
v1 := 3

  

常量

使用const关键字进行定义

const a = 2 + 3.0          // a == 5.0   (untyped floating-point constant)
const b = 15 / 4           // b == 3     (untyped integer constant)
const c = 15 / 4.0         // c == 3.75  (untyped floating-point constant)
const Θ float64 = 3/2      // Θ == 1.0   (type float64, 3/2 is integer division)
const Π float64 = 3/2.     // Π == 1.5   (type float64, 3/2. is float division)
const d = 1 << 3.0         // d == 8     (untyped integer constant)
const e = 1.0 << 3         // e == 8     (untyped integer constant)
const f = int32(1) << 33   // illegal    (constant 8589934592 overflows int32)
const g = float64(2) >> 1  // illegal    (float64(2) is a typed floating-point constant)
const h = "foo" > "bar"    // h == true  (untyped boolean constant)
const j = true             // j == true  (untyped boolean constant)
const k = 'w' + 1          // k == 'x'   (untyped rune constant)
const l = "hi"             // l == "hi"  (untyped string constant)
const m = string(k)        // m == "x"   (type string)
const Σ = 1 - 0.707i       //            (untyped complex constant)
const Δ = Σ + 2.0e-4       //            (untyped complex constant)
const Φ = iota*1i - 1/1i   //            (untyped complex constant)

 有趣的一点,就是Go在一些情况下,会做一些调整,比如:

func  main(){
  a :=8
  a =8.5       // 将编译错误:constant 8.5 truncated to integer
  fmt.Println(a)
}

  

func  main(){
  a := 3
  a = 3.0       // 编译可通过,运行无错误
  fmt.Println(a)
}

  

也就是说,Go在不损失精度的情况下会把3.0这类浮点数视作整数3,如果类型显式指定了,在表达式当中就不会产生变化。在使用的时候会根据上下文需要的类型转化为实际类型,比如uint8(0) + 1.0就是uint8(1),但是uint8(0)+2.2就会由于2.2无法转化为uint8而报错。

当多个常量需要定义时,也可以使用简易写法:

//相同类型的情况:
const c_name1, c_name2 = value1, value2
//可以用作枚举
const (
    Unknown = 0
    Female = 1
    Male = 2
)

 

iota

iota,特殊常量,可以认为是一个可以被编译器修改的常量。在每一个const关键字出现时,被重置为0,然后再下一个const出现之前,每出现一次iota,其所代表的数字会自动增加1

const (
    a = iota  //a = 0
    b = iota  //b = 1
    c = iota  //c = 2
)
//可简写为:
const (
    a = iota
    b
    c
)
//进阶用法:
const (
     i = 1<<iota  // iota=0 i=1
     j = 3<<iota // iota=1 j=6
     k                // iota=2 k=12
     l                // iota=3  l= 24    

 

数组

var array [5]int             //声明
array =  [5]int{1,2,3,4,5}   //初始化
array1 := [5]int{1,2,3,4,5}   //声明并初始化
array2 := [...]int{1,2,3,4,5} //不指定长度进行声明及初始化
array3 := [5]int{1:1,3:4}     //只对索引为1和3的值初始化,其余使用默认初始化值0