English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang 基础教程

Golang 控制语句

Golang 函数 & 方法

Golang 结构体

Golang 切片 & 数组

Golang 字符串(String)

Golang 指针

Golang 接口

Golang 并发

Golang 异常(Error)

Golang 其他杂项

Ключевое слово var в Go

var 关键字Golang用于创建的变量具有一个适当的名称和初始值的特定类型的。var关键字声明变量时,初始化是可选的,我们将在本文后面讨论。

Syntax:

var identifier type = expression
// 这里 w3codebox1 是标识符
//or also called variable name, is of type int, and is assigned the value 200
var w3codebox1 int = 200

As you know, Go is a statically typed language, but it still provides a feature to omit the data type declaration when declaring variables, as shown in the following syntax. This is usually calledtype inference.

Syntax:

var identifier = initialValue
var w3codebox1 = 200

Use the var keyword to declare multiple variables

The var keyword is also used to declare multiple variables in one line. You can also provide initial values for the variables, as shown below:

  • Use the var keyword and type to declare multiple variables:

    var w3codebox1, w3codebox2, w3codebox3, w3codebox4 int
  • Use the var keyword to declare multiple variables, as well as the type and initial value:

    var w3codebox1, w3codebox2, w3codebox3, w3codebox4 int = 10, 20, 30, 40

Note:

  • You can also usetype inference (discussed above)theinferenceThis allows the compiler to know the type, so the type can be removed when declaring multiple variables at the same time.

    var w3codebox1, w3codebox2, w3codebox3, w3codebox4 = 10, 20, 30.30, true
  • You can also declare and initialize different types of values using multiple lines with the var keyword, as shown below:

    var(
         w3codebox1 = 100
         w3codebox2 = 200.57
         w3codebox3 bool
         w3codebox4 string = "ru.oldtoolbag.com"
    )
  • When using the type during declaration, only multiple variables of the same type can be declared. However, if the type is removed during declaration, multiple variables of different types can be declared.

    //use the var keyword to declare variables
    package main
    import "fmt"
    func main() {
        //declare multiple variables of the same type and initialize
        //declare multiple variables of the same type and initialize together in one line
        var w3codebox1, w3codebox2, w3codebox3 int = 232, 784, 854
        //declare multiple variables of different types and initialize
        //не указывать тип в одном строке
        var w3codebox4, w3codebox5, w3codebox6 = 100, "GFG", 7896.46
        fmt.Printf("значение w3codebox1: %d\n", w3codebox1)
        fmt.Printf("Значение w3codebox2 равно: %d\n", w3codebox2)
        fmt.Printf("Значение w3codebox3 равно: %d\n", w3codebox3)
        fmt.Printf("Значение w3codebox4 равно: %d\n", w3codebox4)
        fmt.Printf("Значение w3codebox5 равно: %s\n", w3codebox5)
        fmt.Printf("Значение w3codebox6 равно: %f", w3codebox6)
    }

    Результат:

    Значение w3codebox1 равно: 232
    Значение w3codebox2 равно: 784
    Значение w3codebox3 равно: 854
    Значение w3codebox4 равно: 100
    Значение w3codebox5 равно: GFG
    Значение w3codebox6 равно: 7896.460000

  Основные моменты ключевого слова var:

  • При объявлении переменных с помощью ключевого слова var можно опустить expression type или =, но не оба одновременно. В противном случае компилятор выдаст ошибку...

  • Если удалить выражение, то по умолчанию переменная будет содержать нулевое значение числа и строку, представляющую логическую переменную false, а nil будет содержать типы интерфейсов и ссылки. Таким образом, в языке Go нет концепции неинициализированных переменных.

    //Концепция ключевого слова var
    package main
    import "fmt"
    func main() {
        //Объявление переменных без инициализации
        var w3codebox1 int
        var w3codebox2 string
        var w3codebox3 float64
        var w3codebox4 bool
        //Отображение переменной с нулевым значением
        fmt.Printf("Значение w3codebox1 равно: %d\n", w3codebox1)
        fmt.Printf("Значение w3codebox2 равно: %s\n", w3codebox2)
        fmt.Printf("Значение w3codebox3 равно: %f\n", w3codebox3)
        fmt.Printf("Значение w3codebox4 равно: %t", w3codebox4)
    }

    Результат:

    Значение w3codebox1 равно: 0
    Значение w3codebox2 равно:
    Значение w3codebox3 равно: 0.000000
    Значение w3codebox4 равно: false