DAY 8
1
Modern Web

# 可視範圍

## package

``````package main

var x = 5
``````
``````package main

import "fmt"

func main() {
fmt.Println(x) // 5
}
``````

## package(exported/unexported)

person/personName.go

``````package person

var MyName = "Micheal" // exported
var yourName = "Tony" // unexported
``````
``````package main

import {
"fmt"
"github.com/TroyCode/GoIn30Days/day6/person"
}

func main {
fmt.Println(person.MyName) // Micheal
fmt.Println(person.yourName) // 錯誤，因為是unexported
}
``````

## 括號內的變數{}

``````package main

import "fmt"

func main() {
x := 1
foo() // 錯誤，因為x屬於main中的變數
}

func foo() {
fmt.Println(x)
}
``````

# 全域變數

``````package main

import "fmt"

var x = 0

func xPlus() {
x++
}

func main() {
x++ // x = 1
xPuls() // x = 2
}
``````

# 順序

``````package main

import "fmt"

func main() {
x := 5
fmt.Println(x)
fmt.Println(y) // 這樣是找不到y的
y := 10
}
``````

# 變數和函式名稱相同

``````package main

import "fmt"

func foo(x int) int {
return x + 1
}

func main() {
foo := foo(1) // 第一個foo是變數，第二個是函式
}
``````