📌  相关文章
📜  go variables - Go 编程语言 - Go 编程语言(1)

📅  最后修改于: 2023-12-03 14:41:32.414000             🧑  作者: Mango

Go Variables

In Go programming language, variables are used to store and manipulate data. They are an essential part of any programming language as they allow programmers to work with values and perform operations on them.

Declaring Variables

In Go, variables are declared using the var keyword. The syntax for declaring a variable is as follows:

var variableName dataType

Here, variableName is the name of the variable, and dataType specifies the type of data that the variable can hold. For example, to declare an integer variable called num, you would write:

var num int
Initializing Variables

Variables can be initialized at the time of declaration by assigning a value to them. The syntax for initializing a variable is:

var variableName dataType = value

For example, to declare and initialize a string variable called name with the value "John", you would write:

var name string = "John"

Go also provides a shorter syntax called the "short variable declaration" to declare and initialize variables:

variableName := value

Using the short variable declaration, the above example can be written as:

name := "John"
Variable Types

Go is a statically typed language, which means variables have a specific type that cannot be changed once declared. Here are some commonly used variable types:

  • int: integer values (e.g., 10, -5, 0)
  • float64: floating-point numbers with double precision (e.g., 3.14, -0.5)
  • string: sequence of characters (e.g., "hello", "world")
  • bool: boolean values (true or false)
Constants

In addition to variables, Go also allows the declaration of constants. Constants are like variables, but their values cannot be changed once defined. They are declared using the const keyword and follow the same syntax as variables:

const constantName dataType = value

For example, to declare a constant called pi with the value 3.14159, you would write:

const pi float64 = 3.14159

Constants can also be declared without specifying the data type:

const constantName = value
Conclusion

Variables and constants are fundamental concepts in Go programming language. They allow programmers to store and manipulate data, making programs dynamic and interactive. Understanding how to declare, initialize, and use variables is essential for every Go programmer.