go变量类型声明
- 变量短声明
go语言是强类型语言所以在变量的声明中制定类型,但是在方法中声明的变量可以不需要关键字var以及变量类型,系统
会自动识别, fmt函数中 %v 输出为相应值的默认格式 ,%T 格式化输出该值的类型。
func main() {
a := 10
b := "golang"
c := 4.17
d := true
e := "Hello"
f := `Do you like my hat?`
g := 'M'
fmt.Printf("%v \n", a)
fmt.Printf("%v \n", b)
fmt.Printf("%v \n", c)
fmt.Printf("%v \n", d)
fmt.Printf("%v \n", e)
fmt.Printf("%v \n", f)
fmt.Printf("%v \n", g)
fmt.Printf("%T \n", a)
fmt.Printf("%T \n", b)
fmt.Printf("%T \n", c)
fmt.Printf("%T \n", d)
fmt.Printf("%T \n", e)
fmt.Printf("%T \n", f)
fmt.Printf("%T \n", g)
}
- 变量默认值
func main() {
var a int
var b string
var c float64
var d bool
fmt.Printf("%v \n", a)
fmt.Printf("%v \n", b)
fmt.Printf("%v \n", c)
fmt.Printf("%v \n", d)
}
输出为0 "" 0 false
- 变量带类型先声明后赋值
func main() {
var message string
message = "Hello World."
fmt.Println(message)
}
- 多变量同类型先声明后赋值
func main() {
var message string
var a, b, c int
a = 1
message = "Hello World!"
fmt.Println(message, a, b, c)
}
- 多变量同类型声明同时赋值
func main() {
var message = "Hello World!"
var a, b, c int = 1, 2, 3
fmt.Println(message, a, b, c)
}
- 多变量推断类型(同类型)声明同时赋值
在方法中或者其他代码块中都可以使用,可以定义一个自己不确定的变量类型
func main() {
var message = "Hello World!"
var a, b, c = 1, 2, 3
fmt.Println(message, a, b, c)
}
- 多变量推断类型(不同类型)声明同时赋值
func main() {
var message = "Hello World!"
var a, b, c = 1, false, 3
fmt.Println(message, a, b, c)
}
- 变量各种声明的形式
package main
import "fmt"
var a = "this is stored in the variable a" // package scope
var b, c string = "stored in b", "stored in c" // package scope
var d string // package scope
func main() {
d = "stored in d" // declaration above; assignment here; package scope
var e = 42 // function scope - subsequent variables have func scope:
f := 43
g := "stored in g"
h, i := "stored in h", "stored in i"
j, k, l, m := 44.7, true, false, 'm' // single quotes
n := "n" // double quotes
o := `o` // back ticks
fmt.Println("a - ", a)
fmt.Println("b - ", b)
fmt.Println("c - ", c)
fmt.Println("d - ", d)
fmt.Println("e - ", e)
fmt.Println("f - ", f)
fmt.Println("g - ", g)
fmt.Println("h - ", h)
fmt.Println("i - ", i)
fmt.Println("j - ", j)
fmt.Println("k - ", k)
fmt.Println("l - ", l)
fmt.Println("m - ", m)
fmt.Println("n - ", n)
fmt.Println("o - ", o)
}