Home  >  Article  >  Backend Development  >  The difference between golang constants and variables

The difference between golang constants and variables

(*-*)浩
(*-*)浩Original
2019-12-03 11:53:492935browse

The difference between golang constants and variables

Go language constants

Constant refers to a fixed value that the program may not change during its execution. These fixed values ​​are also called literals. ​ ​ ​ (Recommended learning: go)

A constant can be any basic data type like an integer constant, a floating point constant, a character constant or a string literal. There are also enumeration constants.

The constants are the same, except that their values ​​cannot be modified after being defined by yourself. Conventional variable processing.

Constant definition

With the const keyword, you can specify a friendly name for a literal constant:

const Pi float64 = 3.14159265358979323846
const zero = 0.0 // 无类型浮点常量
const (
size int64 = 1024
eof = -1 // 无类型整型常量
)
const u, v float32 = 0, 3 // u = 0.0, v = 3.0,常量的多重赋值
const a, b, c = 3, 4, "foo"
// a = 3, b = 4, c = "foo", 无类型整型和字符串常量

Go language variable

A variable is nothing but a name given to a storage area that our program can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable memory; can determine the range of values ​​stored within the memory; and group operations can be applied to the variable.

A variable name can consist of letters, numbers and underscores. It must start with a letter or underline. Uppercase and lowercase letters are different because Go is case-sensitive.

Initialization of variables

For scenarios that require initialization when declaring variables, the var keyword can be retained, but it is no longer a necessary element, as shown below:

var v1 int = 10 // 正确的使用方式1
var v2 = 10 // 正确的使用方式2,编译器可以自动推导出v2的类型
v3 := 10 // 正确的使用方式3,编译器可以自动推导出v3的类型

The above is the detailed content of The difference between golang constants and variables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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

Related articles

See more