# Go教程第三篇:变量

## 什么是变量

#### 声明单一变量

package main

import "fmt"

func main() {
var age int // 变量声明
fmt.Println("my age is", age)
}

var age int 语句声明了一个名称为age，数据类型为int的变量。我们没有为该变量指定任何值。

my age is 0

package main

import "fmt"

func main() {
var age int // variable declaration
fmt.Println("my age is ", age)
age = 29 //assignment
fmt.Println("my age is", age)
age = 54 //assignment
fmt.Println("my new age is", age)
}

my age is  0
my age is 29
my new age is 54

## 声明一个有初始值的变量

var name type =initialvalue

package main

import "fmt"

func main() {
var age int = 29 //变量声明时给定初始值

fmt.Println("my age is", age)
}

，你可以看到如下输出。这也就表明age已经被初始化了一个29的值。

my age is 29


## 类型引用

go可以很轻易地推断出它的类型是int。

package main

import "fmt"

func main() {
var age = 29 // 自动推断变量类型

fmt.Println("my age is", age)
}

## 多变量声明

var name1, name2 type = initialvalue1,initialvalue2


package main

import "fmt"

func main() {
var width, height int = 100, 50 //声明多个变量

fmt.Println("width is", width, "height is", height)
}

package main

import "fmt"

func main() {
var width, height = 100, 50 //"int" 被丢弃了

fmt.Println("width is", width, "height is", height)
}

package main

import "fmt"

func main() {
var width, height int
fmt.Println("width is", width, "height is", height)
width = 100
height = 50
fmt.Println("new width is", width, "new height is ", height)
}

width is 0 height is 0
new width is 100 new height is  50

var (
name1 = initialvalue1
name2 = initialvalue2
)

package main

import "fmt"

func main() {
var (
name   = "naveen"
age    = 29
height int
)
fmt.Println("my name is", name, ", age is", age, "and height is", height)
}

## 快捷声明(short hand declaration)

Go 也提供了另一种简洁方式声明变量。也被称为 快捷声明，它使用 := 操作符来做到这一点。

name :=initialvale

package main

import "fmt"

func main() {
name, age := "naveen", 29 //short hand declaration

fmt.Println("my name is", name, "age is", age)
}

package main

import "fmt"

func main() {
name, age := "naveen" //错误

fmt.Println("my name is", name, "age is", age)
}

package main

import "fmt"

func main() {
a, b := 20, 30 // declare variables a and b
fmt.Println("a is", a, "b is", b)
b, c := 40, 50 // b is already declared but c is new
fmt.Println("b is", b, "c is", c)
b, c = 80, 90 // assign new values to already declared variables b and c
fmt.Println("changed b is", b, "c is", c)
}

a is 20 b is 30
b is 40 c is 50
changed b is 80 c is 90

package main

import "fmt"

func main() {
a, b := 20, 30 //a and b declared
fmt.Println("a is", a, "b is", b)
a, b := 40, 50 //error, no new variables
}

package main

import (
"fmt"
"math"
)

func main() {
a, b := 145.8, 543.8
c := math.Min(a, b)
fmt.Println("minimum value is ", c)
}

minimum value is 145.8


package main

func main() {
age := 29      // age is int
age = "naveen" // error since we are trying to assign a string to a variable of type int
}