Go language constant decryption: constant values (const and iota) (with code examples)

Table of Contents

Declaration and definition of constants

Declare constants in batches

Complete code example

Constant naming rules

Common constant types

iota

Code example 1

Code example 2

Code example 3

Code example 4

Constant usage scenarios

Summarize


Picture

?Original text: Go language constant decryption: constant values (const and iota) (with code examples)

For more related technical points about Go, please pay attention to the public account: CTO Plus for subsequent posts. If you have any questions, please leave a message in the background for communication.

Variables and constants are an essential part of programming. In the previous article of the public account CTO Plus, I introduced the use of variables (identifiers) and constants, and used code examples to demonstrate their features. For details, please refer to The previous article of the public account CTO Plus is “Exploring Go Language Variables and Identifiers: Flexible Storage of Data”. The next article will introduce the scope of variables “The Life Cycle and Scope of Go Language Variables”.

Compared with variables, constants in the Go language are fixed values whose values cannot be modified while the program is running. They are mostly used to define values that will not change while the program is running. Constants are used in programs to store immutable data, such as mathematical constants (such as PI), fixed configuration parameters, etc.

In this article, I will introduce in detail the declaration and various definition methods, naming rules, and common constant types of constants in the Go language. I will also introduce the constant counter iota and use 4 code examples to give a detailed functional demonstration. Finally, I will introduce constants. usage scenarios.

Picture?

Declaration and Definition of Constants

In the Go language, the declaration of constants is very similar to the declaration of variables, except that var is replaced by const. Constants must be assigned values when they are defined. The syntax is as follows:

Constants are declared using the keyword const

const constant name type = value

For example, if you declare a constant maxAge of integer type and a PI of no explicitly specified type, the values of these two variables cannot change during the entire program running:

const maxAge int = 100

const PI = 3.1415926

If you use := to define a constant, a syntax error will be reported.

const NUM := 0 // syntax error: unexpected :=, expected =

Batch declaration of constants

Multiple constants can also be declared together:

const (</code><code> BLOG = "https://mp.weixin.qq.com/s/0yqGBPbOI6QxHqK17WxU8Q"</code><code> WECHAT = "CTO Plus"</code><code>) 

When declaring constants in batches, if = is not written in a line, it will be the same as the previous line.

// When const declares multiple constants at the same time, if the value is omitted, it means the same value as the above line</code><code>const (</code><code> maxAge = 100</code><code> age2</code><code> age3</code><code>)

In the above example, the values of the constants maxAge, age2, and age3 are all 100.

But the first variable must be assigned a value, otherwise the compiler will report an error

const (</code><code> num1 // missing init expr for num1</code><code> num2</code><code> num3</code><code>)

Some notes on using constants:

1. When defining, a value must be specified.

2. There are three main types of specified value types: Boolean, number, and string. Number types include (rune, integer, floating-point, complex), which are all basic data types.

3. Cannot use :=.

4. The declaration and assignment of constants are performed at the same time, so there is no need to use the equal sign = for assignment operations. If you use = to assign values again, a compilation error will occur.

For more related technical points about Go, please pay attention to the public account: CTO Plus for subsequent posts. If you have any questions, please leave a message in the background for communication.

Picture?

Full code example

package main
import "fmt"
/*1. When defining, the value must be specified2. There are three main types of specified value types: Boolean, number, string, among which the number type includes ( rune, integer, floating-point, complex), they all belong to basic data types. 3. Cannot be used:=*/func constVar() { const maxAge int = 100 const PI = 3.1415926
 fmt.Println(maxAge) //maxAge = 0 // cannot assign to maxAge (constant 100 of type int)
 const num = 1234 // num = 123 //erro cannot assign to num (untyped int constant 1234)
 const ( num1 = 1000 num2 = 2.222 ) // num1 = 123 // error cannot assign to num1 fmt.Println(num, num1 + num2)}
//Global constants declare multiple constants togetherconst ( BLOG = "https://mp.weixin.qq.com/s/0yqGBPbOI6QxHqK17WxU8Q" WECHAT = "CTO Plus")
// When const declares multiple constants at the same time, if the value is omitted, it means the same value as the above line</code><code>const (</code><code> maxAge = 100</code><code> age2</code><code> age3</code><code>)
func main() { constVar() fmt.Println(BLOG) // https://mp.weixin.qq. com/s/0yqGBPbOI6QxHqK17WxU8Q fmt.Println(WECHAT) // CTO Plus fmt.Println(maxAge, age2, age3) // CTO Plus }

Constant naming rules

In the Go language, the naming of constants needs to follow some rules:

  • Constant names consist of letters, numbers, and underscores, and must start with a letter or underscore.

  • Constant names are case-sensitive, and maxAge and MaxAge are different constants.

  • Avoid using Go language keywords as constant names, such as if, for, etc.

  • Constant names should be descriptive and clearly convey the meaning of the constant.

Generally speaking, the naming style of Go language adopts camel case naming method, that is, the first letter is lowercase, and the first letter of subsequent words is capitalized, such as maxAge and piValue.

For more related technical points about Go, please pay attention to the public account: CTO Plus for subsequent posts. If you have any questions, please leave a message in the background for communication.

Picture?

Common constant types< /strong>

The Go language provides a variety of constant types. Common constant types include:

  • Integer types: int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, etc.

  • Floating point number types: float32, float64.

  • Boolean type: bool, the value is true or false.

  • String type: string.

  • Character type: byte, used to represent ASCII characters.

In addition to basic data types, the Go language also provides constants of composite types, such as arrays, slices, maps, structures, etc., for storing multiple values or values of different types.

Next, let’s introduce another keyword iota related to constants.

iota

In the Go language, iota is a special constant that can be used as an incrementing counter (constant counter) for enumeration values and can only be used in constant expressions. iota is reset to 0 every time the const keyword appears, and every time iota appears, its value will increase by 1 (iota can be understood as the row index in the const statement block).

Code Example 1

Using iota can simplify definitions and is useful when defining enumerations. Here are some usage examples of iota:

Picture?

In the above example, the value of Monday is iota + 1, which is 1. The value of Tuesday is iota + 1, which is 2. By analogy, the value of each constant will be calculated according to iota's auto-increment rules.

For more related technical points about Go, please pay attention to the public account: CTO Plus for subsequent posts. If you have any questions, please leave a message in the background for communication.

Picture?

Code Example 2

iota can also be used to define a set of related constants, where the value of each constant is twice the value of the previous constant. Here's an example:

package main</code>
<code>import "fmt"</code>
<code>func iotaFunc2() {<!-- --></code><code> const (</code><code> KB = 1 << (10 * iota) // 1 is shifted left by 10 bits, that is 1024</code><code> MB // Shift 1 to the left by 20 bits, that is, 1024*1024</code><code> GB // Shift 1 to the left by 30 bits, that is, 1024*1024*1024</code><code> TB // 1 is shifted 40 bits to the left, that is, 1024*1024*1024*1024</code><code> )</code>
<code> fmt.Println(KB) // Output: 1</code><code> fmt.Println(MB) // Output: 1024</code><code> fmt.Println(GB) // Output: 1048576 </code><code> fmt.Println(TB) // Output: 1073741824</code><code>}

In the above example, the value of KB is 1 << (10 * iota), that is, 1 is shifted to the left by 10 bits, that is, it changes from 1 to 10000000000, which is 1024. The value of MB is 1 << (10 * iota), that is, 1 is shifted to the left by 20 bits, which is 1024*1024. By analogy, the value of each constant is twice the previous constant.

Code Example 3

iota can also be used for bit operations, such as defining a set of permission constants:

package main</code>
<code>import "fmt"</code>
<code>const (</code><code> ReadPermission = 1 << iota // Shift 1 to the left by 0 bits, which is 1</code><code> WritePermission // Shift 1 to the left by 1 bit, which is 2</code> <code> ExecutePermission // 1 is shifted left by 2 bits, which is 4</code><code>)</code>
<code>func main() {<!-- --></code><code> var permission int = ReadPermission | WritePermission</code>
<code> fmt.Println(permission & amp;ReadPermission == ReadPermission) // Output: true</code><code> fmt.Println(permission & amp;WritePermission == WritePermission) // Output: true</code> <code> fmt.Println(permission & amp;ExecutePermission == ExecutePermission) // Output: false</code><code>}

In the above example, the value of ReadPermission is 1 << iota, that is, 1 is shifted 0 bits to the left, which is 1. The value of WritePermission is 1 << iota, that is, 1 is shifted to the left by 1 bit, which is 2. By analogy, the value of each constant is twice the previous constant. Finally, we can use bit operations to determine whether a certain permission is set.

For more related technical points about Go, please pay attention to the public account: CTO Plus for subsequent posts. If you have any questions, please leave a message in the background for communication.

Picture?

Code Example 4

Combined with_skipping certain values, iota's queue-jumping definition, example of using iota definition in multiple lines

func iotafFunc4() {<!-- --></code><code> //Use _ to skip certain values</code><code> const (</code><code> num1 = iota </code><code> _ // _ also occupies one line, so the value of _ is equivalent to 1</code><code> num3</code><code> _</code><code> num5</code><code> )</code><code> // Here again the assignment of const jump iota</code><code> const (</code><code> num6 = iota</code><code> num7 // num6=iota, so the value of num6 is 0; num7 does not have =, so the value is deduced to 1</code><code> num8 = 123 // Because num8=123, and num9 does not have =, so it is the same as the value of num9 To remain consistent, they are all 123</code><code> num9</code><code> num10 = iota</code><code> num11</code><code> )</code><code> fmt.Println( num1, num3, num5, num6, num7, num8, num9, num10, num11) // 0 2 4 0 1 123 123 4 5</code>
<code> //Multiple iota definitions in one line</code><code> const (</code><code> n1, n2 = iota + 1, iota + 2</code><code> n3, n4</code><code> n5, n6</code><code> n7, n8</code><code> // n9, n10, n11 incorrect usage, the number of variables in each row must be consistent with the first row</code><code> // n9, n10, n11, n12 //missing init expr for n11</code><code> )</code><code> fmt.Println(n1, n2, n3, n4, n5, n6, n7, n8) // 1 2 2 3 3 4 4 5</code>
<code> const (</code><code> n11, n12 = iota + 1, iota + 1</code><code> n13, n14 = iota + 1, iota + 1</code><code> )</code><code> fmt.Println(n11, n12, n13, n14) // 1 1 2 2</code><code>}

Usage scenarios of constants< /strong>

Constants are used to store immutable data in programs. Common usage scenarios include:

  • Mathematical constants: such as pi, the base of natural logarithms, e, etc.

  • Fixed configuration parameters: such as database connection string, API key, etc.

  • Enumeration type: A set of related constants is defined as an enumeration type, used to represent a fixed set of values.

The use of constants can improve the readability and maintainability of the program, avoid using magic numbers in the program, and make the program clearer and easier to understand.

For more related technical points about Go, please pay attention to the public account: CTO Plus for subsequent posts. If you have any questions, please leave a message in the background for communication.

Picture?

Summary

In general, a constant in the Go language is a fixed value used to store unchanged data. The const keyword is used to define constants. After definition, they cannot be modified or assigned again. They will not change during the running of the program. The naming of constants needs to follow certain rules.

  • Constant types include integer types, floating point types, Boolean types, string types, etc. The usage scenarios of constants include mathematical constants, fixed configuration parameters, enumeration types, etc.

  • iota is a special constant used as an incrementing counter for enumeration values.

  • iota is reset to 0 on each occurrence of the const keyword, and its value is incremented by 1 each time iota appears.

  • iota can be used to define a set of related constants, where the value of each constant is twice the value of the previous constant.

  • iota can also be used for bit operations, such as defining a set of permission constants.

By rationally using constants, you can improve the readability and maintainability of your program.

For more excitement, follow my official account and learn and grow together

Picture?

?

Recommended reading:

  • Open source projects | 17 cloud-native security-related scanning and platform open source tools

  • Go language constant decryption: constant values (const and iota) (with code examples)
    In-depth understanding of data types in Go language

  • Use strconv to convert Go's int, float, and string types to and from each other: Flexible conversion of data types

  • The life cycle and scope of Go language variables

  • String traversal techniques in Go: easily manipulate text

  • Go language string operation secrets: efficient text processing

  • Comprehensive analysis and pitfalls of Go's process control (if, for, switch, goto)

  • Detailed explanation of Go's multi-terminal development environment and compiler construction (pictures and text)

  • Advanced features, development trends, and recommendations of the most popular open source projects of the Go language

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Go skill treeFirst glimpse of the doorgo variables and constants 4350 people are learning the system

syntaxbug.com © 2021 All Rights Reserved.