How to define variable scope in Golang function?

WBOY
Release: 2024-04-11 12:27:01
Original
761 people have browsed it

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

How to define variable scope in Golang function?

Function scope variable definition in Go

In Go, function scope determines the visibility of variables. Variables declared inside a function can only be accessed within that function.

Variable declaration

The way to declare variables in a function is as follows:

var name string = "Alice"
Copy after login

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.

Scope

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) // 错误
}
Copy after login

Practical case: Calculating the area of ​​a triangle

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
}
Copy after login

In In the above example:

  • Function area declares a local variable area.
  • Variable area is valid in function area, but not in main function main.
  • Main function 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!