What is const in golang?

(*-*)浩
Release: 2019-12-31 13:48:15
Original
5806 people have browsed it

What is const in golang?

#The const declaration provides a name for a constant, a value that is fixed at compile time. The value of a constant must be a number, string, or boolean.

Constants in the Go language are defined using the keyword const, which is used to store data that will not change. Constants are created at compile time, even if they are defined inside a function, and can only be Boolean, numeric (integer, floating point and complex) and string. (Recommended learning: Go )

# Because due to the limitation of compilation, the expression of the constant constant must be the constant expression that can be used to be worth the compiler.

The definition format of constants is similar to the declaration syntax of variables: const name [type] = value, for example:

const pi = 3.14159 // 相当于 math.Pi 的近似值
Copy after login

In Go language, you can omit the type specifier [type ] because the compiler can infer the type of a variable based on its value.

Explicit type definition: const b string = "abc"

Implicit type definition: const b = "abc"

The value of the constant must be able to be compiled at compile time To be sure, calculations can be involved in their assignment expressions, but all values ​​used for calculations must be available at compile time.

Correct approach:

const c1 = 2/3
Copy after login

Incorrect approach:

const c2 = getNumber() // 引发构建错误: getNumber() 用做值
Copy after login

Same as variable declaration, multiple constants can be declared in batches:

const (
    e  = 2.7182818
    pi = 3.1415926
)
Copy after login

All constants Operations can be completed at compile time, which not only reduces runtime work, but also facilitates the compilation and optimization of other codes. When the operand is a constant, some runtime errors can also be discovered at compile time, such as integer division by zero, String index out of bounds, any operation resulting in an invalid floating point number, etc.

The results of all arithmetic operations, logical operations and comparison operations between constants are also constants. Type conversion operations on constants or the following function calls return constant results: len, cap, real, imag, complex and unsafe .Sizeof.

The above is the detailed content of What is const in golang?. 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