01.變數定義

JJJhr發表於2024-07-06

變數定義

新建專案

func variableZeroValue() {
    //賦空值
    var a int
    var s string
    fmt.Printf("%d %q\n", a, s)
}

變數賦空值

func variableZeroValue() {
    //賦空值
    var a int
    var s string
    fmt.Printf("%d %q\n", a, s)
}

變數賦初值

func variableInitialValue() {
    //初始變數,Go語言非常嚴格,定義了就要用到
    //定義多個變數可賦初值也可不賦
    var a, b int = 3, 4
    var s string = "abc"
    fmt.Println(a, b, s)
}

推測變數型別

func variableTypeDeduction() {
    //推斷型別
    var a, b, c, d = 3, 4, true, "def"
    println(a, b, c, d)
}

簡寫(:=只能函式內使用)

func variableShorter() {
  //簡寫 a, b, c, d :
= 3, 4, true, "def" b = 7 fmt.Println(a, b, c, d) }

函式外定義變數

var name = "jj"
var age = 24
var (
    name1 = "aa"
    age1  = 22
)

程式碼:

package main

import "fmt"

func variableZeroValue() {
    //賦空值
    var a int
    var s string
    fmt.Printf("%d %q\n", a, s)
}

func variableInitialValue() {
    //初始變數,Go語言非常嚴格,定義了就要用到
    //定義多個變數可賦初值也可不賦
    var a, b int = 3, 4
    var s string = "abc"
    fmt.Println(a, b, s)
}

func variableTypeDeduction() {
    //推斷型別
    var a, b, c, d = 3, 4, true, "def"
    println(a, b, c, d)
}

func variableShorter() {
    a, b, c, d := 3, 4, true, "def"
    b = 7
    fmt.Println(a, b, c, d)
}

var name = "jj"
var age = 24
var (
    name1 = "aa"
    age1  = 22
)

func main() {
    fmt.Println("Hello World")
    variableZeroValue()
    variableInitialValue()
    variableTypeDeduction()
    variableShorter()
    fmt.Println(name, age)
    fmt.Println(name1, age1)
}

相關文章