05.变量声明

1.总结

2.示例代码

package main

import "fmt"

// 声明全局变量 方法一、方法二、方法三 是可以的
var gA int = 100
var gB = 200

// 用方法四声明全局变量
// := 只能够用在 函数体内来声明
// gC := 200

// main func
func main() {
    // 方法一:声明一个变量 默认的值是0
    var a int
    fmt.Println("a = ", a)
    fmt.Printf("type of a = %T\n", a)

    // 方法二:声明一个变量,初始化一个值
    var b int = 100
    fmt.Println("b = ", b)
    fmt.Printf("type of b = %T\n", b)

    // 方法三:在初始化的时候,可以省去数据类型,通过值自动匹配当前的变量的数据类型
    var c = 100
    fmt.Println("c = ", c)
    fmt.Printf("type of c = %T\n", c)

    e := 200
    fmt.Println("e = ", e)
    fmt.Printf("type of e = %T\n", e)

    f := "abcd"
    fmt.Println("f = ", f)
    fmt.Printf("type of f = %T\n", f)

    g := 3.14
    fmt.Println("g = ", g)
    fmt.Printf("type of f = %T", g)

    // =====
    fmt.Println("gA = ", gA, ", gB = ", gB)
    //fmt.Println("gC = ", gC)

    // 声明多个变量
    var xx, yy int = 100, 200
    fmt.Println("xx = ", xx, ", yy = ", yy)
    var kk, ll = 100, "hello world"
    fmt.Println("kk = ", kk, ", ll = ", ll)

    var (
        vv int  = 100
        jj bool = true
    )
    fmt.Println("vv = ", vv, ", jj = ", jj)

}

//执行结果
a =  0
type of a = int
b =  100
type of b = int
c =  100
type of c = int
e =  200
type of e = int
f =  abcd
type of f = string
g =  3.14
type of f = float64gA =  100 , gB =  200
xx =  100 , yy =  200
kk =  100 , ll =  hello world
vv =  100 , jj =  true

3.扩展

3.1.intxxx默认值

var a int
var b int8
var c int16
var d int32
var e int64

fmt.Println("int的默认值")
fmt.Println("a = ", a, ", b = ", b, ", c = ", c, ", d = ", d, ", e = ", e)
fmt.Printf("type of a = %T\n", a)
fmt.Printf("type of b = %T\n", b)
fmt.Printf("type of c = %T\n", c)
fmt.Printf("type of d = %T\n", d)
fmt.Printf("type of e = %T\n", e)

// 执行结果
int的默认值
a =  0 , b =  0 , c =  0 , d =  0 , e =  0
type of a = int
type of b = int8
type of c = int16
type of d = int32
type of e = int64

3.2.float默认值

var a float32
var b float64
fmt.Println("float的默认值")
fmt.Println("a = ", a, ", b = ", b)
fmt.Printf("type of a = %T\n", a)
fmt.Printf("type of b = %T\n", b)
//执行结果
float的默认值
a =  0 , b =  0
type of a = float32
type of b = float64

3.3.bool默认值

var a bool
fmt.Println("bool的默认值")
fmt.Println("a = ", a)
fmt.Printf("type of a = %T\n", a)
//执行结果
bool的默认值
a =  false
type of a = bool

3.4.string默认值

var a string
fmt.Println("string的默认值")
fmt.Println("a = ", a)
fmt.Printf("type of a = %T\n", a)
fmt.Printf("len of a = %d\n", len(a))
//执行结果
string的默认值
a =
type of a = string
len of a = 0

3.5.char默认值

var a complex64
var b complex128
fmt.Println("complex的默认值")
fmt.Println("a = ", a, ", b = ", b)
fmt.Printf("type of a = %T\n", a)
fmt.Printf("type of b = %T\n", b)
// 执行结果
complex的默认值
a =  (0+0i) , b =  (0+0i)
type of a = complex64
type of b = complex128
posted @ 2021-10-07 18:01  可可逗豆  阅读(35)  评论(0)    收藏  举报