In Go, function scope limits variable visibility to the function where the variable is declared: Declare a variable within a function: var name type = value Scope is limited to the declared code block, other functions or nested blocks These variables cannot be accessed
In Go, function scope determines the visibility of variables. Variables declared inside a function can only be accessed within that function.
The way to declare variables in a function is as follows:
var name string = "Alice"
Among them:
var
Keywords Indicates declaring a new variable. name
is the name of the variable. string
is the type of the variable. = "Alice"
Initialize the value of the variable. In Go, the scope of a variable is limited to the code block in which it is declared. This means that these variables cannot be accessed within other functions or nested blocks.
For example:
func main() { age := 20 fmt.Println(age) // 输出:20 } func other() { // age 未定义 fmt.Println(age) // 错误 }
In order to demonstrate the function scope, we write a function to calculate the area of a triangle:
func area(base, height float64) float64 { // 定义局部变量面积 var area float64 // 计算三角形面积 area = 0.5 * base * height return area } func main() { // 在主函数中调用 area 函数并打印面积 fmt.Println(area(5.0, 10.0)) // 输出:25.0 }
In In the above example:
area
declares a local variable area
. area
is valid in function area
, but not in main function main
. main
Use fmt.Println
to print the return value of the area
function. The above is the detailed content of How to define variable scope in Golang function?. For more information, please follow other related articles on the PHP Chinese website!