Technology Sharing

【Go】Common variables and constants

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

variable

Common variable declaration methods

1. Multiple ways to declare a single variable

1. Declare a variable and initialize a value
  1. //声明变量 默认值是0,
  2. var a int
  3. //初始化一个值
  4. a = 1
  5. fmt.Println(a)
2. Omit during initializationtype of data, automatically matches the data type of the current variable through the value
  1. var b = 2
  2. fmt.Println("初始化值:", b)

3. Omit the var keyword and match automatically (cannot be used for global variables, only in function bodies)
  1. c := 3
  2. fmt.Println("初始化值:", c)

As follows, := cannotDeclaring global variables

2. How to declare multiple variables

  1. //声明多个变量
  2. var h, i int = 10, 11
  3. fmt.Printf("h=%d,i=%dn", h, i)
  4. //多行的变量声明
  5. var (
  6. vv int = 100
  7. jj bool = true
  8. )
  9. fmt.Println("vv=", vv, "jj=", jj)

The overall code demonstration is as follows:

  1. package main
  2. import "fmt"
  3. var d int = 4
  4. var e = 5
  5. func main() {
  6. //变量声明方法
  7. 声明变量 默认值是0
  8. var a int
  9. //初始化一个值
  10. a = 1
  11. fmt.Println("a初始化值:", a)
  12. //
  13. //初始化的时候省去数据类型,通过自动匹配当前的变量的数据类型
  14. var b = 2
  15. fmt.Println("b初始化值:", b)
  16. //
  17. //
  18. c := 3
  19. fmt.Println("c初始化值:", c)
  20. //
  21. //
  22. 打印全局变量
  23. fmt.Println("全局变量d=", d)
  24. fmt.Println("全局变量e=", e)
  25. fmt.Println("===================")
  26. //声明多个变量
  27. var h, i int = 10, 11
  28. fmt.Printf("h=%d,i=%dn", h, i)
  29. //多行的变量声明
  30. var (
  31. vv int = 100
  32. jj bool = true
  33. )
  34. fmt.Println("vv=", vv, "jj=", jj)
  35. }

constant

1. const

A constant is a simple identifier that does not change while the program is running.

The data types in constants can only be Boolean, numeric,Stringtype

The definition format of a constant is:

const identifier  [type] =value

The compiler can infer the type based on the value of the variable, and the type can be omitted

Display type definitions:

  1. //显示常量类型
  2. const a string = "五敷"
  3. fmt.Print("常量a:", a)

Implicit constant types

  1. //隐式常量类型
  2. const b = "有你"
  3. fmt.Println("常量b", b)
多个定义常量
  1. const (
  2. c = 0
  3. d = 1
  4. e = 2
  5. )
  6. fmt.Printf("c:%d,d:%d,e:%d", c, d, e)

2. iota and expressions

 iotacan do more than just increment. More precisely,iotaAlways used for increment, but it can be used in expressions, storing the resulting value in a constant.

  1. const (
  2. aa = iota + 1
  3. bb = iota + 100 //会沿用iota的值
  4. )
  5. fmt.Printf("aa=%d,bb=%d", aa, bb)
  6. //iota总是用于 increment,但是它可以用于表达式
  7. const (
  8. express1, express2 = iota + 1, iota + 2
  9. express3, express4
  10. express5, express6
  11. )
  12. fmt.Println("express1,express2,express3,express4=>", express1, express2, express3, express4, express5, express6)

Note: iota can only be used in const