Go programming example [constant]

base instance

Go supports character, string, boolean and numeric constants.

// constant.go
package main

import (
	"fmt"
	"math"
)

// `const` 用于声明一个常量。
const s string = "constant"

func main() {
    
    
	fmt.Println(s)

	// `const` 语句可以出现在任何 `var` 语句可以出现的地方
	const n = 500000000

	// 常数表达式可以执行任意精度的运算
	const d = 3e20 / n
	fmt.Println(d)

	// 数值型常量没有确定的类型,直到被给定,
	// 比如一次显式的类型转化。
	fmt.Println(int64(d))

	// 当上下文需要时,比如变量赋值或者函数调用,
	// 一个数可以被给定一个类型。举个例子,
	// 这里的 `math.Sin` 函数需要一个 `float64` 的参数。
	fmt.Println(math.Sin(n))
}
[root@bogon test]# go constant.go
constant
6e+11
600000000000
-0.28470407323754404
[root@bogon test]# 

brief constant

definition

In the Go language, the term "constant" is used to denote a fixed value.
Such as 5, -89, I love Go, 67.89 and so on.

Take a look at the code below:

var a int = 50
var b string = "I love Go"

In the above code, the variables a and b are assigned the constants 50 and I love GO, respectively.
The keyword const is used to represent constants, such as 50 and I love Go.
Even though we didn't explicitly use the keyword const in the above code, internally in Go, they are constants.

As the name implies, constants cannot be reassigned to other values.
So the following program will not work properly,
it will throw a compilation error: cannot assign to a..

package main

func main() {
    
    
    const a = 55 // 允许
    a = 89       // 不允许重新赋值
}

The value of the constant is determined at compile time.
Because a function call occurs at runtime, you cannot assign the return value of a function to a constant.

package main

import (
    "fmt"
    "math"
)

func main() {
    
    
    fmt.Println("Hello, playground")
    // math包中的Sqrt函数来计算一个数的平方根。
    var a = math.Sqrt(4)   // 允许
    fmt.Println(a) // 2
    const b = math.Sqrt(4) // 不允许
}

In the above program, because a is a variable, we can assign the return value of the function math.Sqrt(4) to it.

b is a constant whose value needs to be determined at compile time.

The function math.Sqrt(4) will only be evaluated at runtime, so const b = math.Sqrt(4) will throw an error error main.go:11: const initializer math.Sqrt(4) is not a constant) .

string constant

Any value enclosed in double quotes is a string constant in Go.
For example strings like Hello World or Sam are constants in Go.

What types of strings are constants?
The answer is that they are untyped.

A string constant like Hello World doesn't have any type.

const hello = "Hello World"

In the above example, we assigned Hello World to the constant hello.

Does the constant hello now have a type?
The answer is 没有.
Constants still have no type.

Go is a strongly typed language, all variables must have a clear type.

So, how does the following program assign the untyped constant Sam to the variable name?

package main

import (
    "fmt"
)

func main() {
    
    
    var name = "Sam"
    fmt.Printf("type %T value %v", name, name)
	// type string value Sam
}

The answer is that untyped constants have a default type associated with them, and that is provided if and only if a line of code requires it.

In the declaration var name = "Sam", name requires a type, which is taken from the default type of the string constant Sam.

Is there a way to create a constant with a type?
The answer is yes.
The following code creates a typed constant.

const typedhello string = "Hello World"

In the above code, typedhello is a constant of type string.

Go is a strongly typed language and mixing types during assignment is not allowed.
Let's see what this sentence means with the following program.

package main

func main() {
    
    
     var defaultName = "Sam" // 允许
     
     type myString string
     var customName myString = "Sam" // 允许
     
     customName = defaultName // 不允许
}

In the above code, we first create a variable defaultName and assign a constant Sam.
The default type of constant Sam is string, so defaultName is of string type after assignment.

On the next line, we create a new type myString, which is an alias for string.

Then we create a variable customName of myString and assign it the constant Sam. Because the constant Sam is untyped, it can be assigned to any string variable.

So this assignment is allowed and the type of customName is myString.

We now have a variable defaultName of type string and another variable customName of type myString. Even though we know that myString is an alias of type string. Go's type strategy does not allow assigning a variable of one type to a variable of another type. So assigning defaultName to customName is not allowed, and the compiler throws an error main.go:7:20: cannot use defaultName (type string) as type myString in assignmen.

boolean constant

Boolean constants are no different than string constants. They are two untyped constants true and false.

The rules for string constants apply to boolean constants, so we won't repeat them here.

Following is a simple program that interprets boolean constants.

package main

func main() {
    
    
	// 定义一个常量 trueConst,并赋值为 true
	const trueConst = true
	// 定义一个新类型 myBool,它的底层类型是 bool
	type myBool bool
	// 定义一个变量 defaultBool,并将 trueConst 赋值给它,允许赋值
	var defaultBool = trueConst
	// 定义一个变量 customBool,将 trueConst 赋值给它,允许赋值
	var customBool myBool = trueConst

	// 将 customBool 赋值给 defaultBool,不允许赋值,会在编译时报错
	defaultBool = customBool
}

numeric constant

Numeric constants include integer, floating-point, and complex constants.
There are some subtleties in numeric constants.

Let's see some examples to make it clear.

package main

import (
	"fmt"
)

func main() {
    
    
	const a = 5
	var intVar int = a
	var int32Var int32 = a
	var float64Var float64 = a
	var complex64Var complex64 = a
	
	fmt.Println("intVar", intVar,
		"\nint32Var", int32Var,
		"\nfloat64Var", float64Var,
		"\ncomplex64Var", complex64Var)
}
[root@localhost test]# go run hello.go 
intVar 5 
int32Var 5 
float64Var 5 
complex64Var (5+0i)
[root@localhost test]# 

In the above program, the constant a has no type and its value is 5.

You might be wondering what the default type of a is, and if it does have one, then how we can assign it to a variable of a different type.

The answer lies in the syntax of a.

The program below will make things clearer.

package main

import (
	"fmt"
)

func main() {
    
    
	var i = 5
	var f = 5.6
	var c = 5 + 6i
	fmt.Printf("i's type %T, f's type %T, c's type %T", i, f, c)
	// i's type int, f's type float64, c's type complex128
}

In the above program, the type of each variable is determined by the syntax of numeric constants.

5 is syntactically an integer, 5.6 is a floating point number, and 5+6i is syntactically complex.

When we run the above program, it will print i's type int, f's type float64, c's type complex128.

Now I want the following program to work correctly.

package main

import (
	"fmt"
)

func main() {
    
    
	const a = 5
	var intVar int = a
	var int32Var int32 = a
	var float64Var float64 = a
	var complex64Var complex64 = a

	fmt.Println("intVar", intVar,
		"\nint32Var", int32Var,
		"\nfloat64Var", float64Var,
		"\ncomplex64Var", complex64Var)
}
[root@localhost test]# go run hello.go 
intVar 5 
int32Var 5 
float64Var 5 
complex64Var (5+0i)
[root@localhost test]#

In this program, the value of a is 5, and the syntax of a is generic (it can represent a floating-point number, an integer, or even a complex number with no imaginary part), so it can be assigned to any compatible type.

The default types for these constants can be thought of as being generated on the fly according to the context.

var intVar int = a requires a to be int, so it becomes an int constant.

var complex64Var complex64 = a requires a to be complex64, so it becomes a complex type. Very simple:).

numeric expression

Numeric constants can be freely mixed and matched in expressions, and types are only required when they are assigned to variables or used anywhere in code that requires types.

package main

import (
	"fmt"
)

func main() {
    
    
	var a = 5.9 / 8
	fmt.Printf("a's type %T value %v", a, a)
	// a's type float64 value 0.7375
}

In the above program, 5.9 is syntactically a float, 8 is an integer, and 5.9/8 is allowed because both are numeric constants.

The result of the division is 0.7375 which is a float, so the type of a is float.

The output of this program is: a's type float64 value 0.7375.

Guess you like

Origin blog.csdn.net/weiguang102/article/details/129734865