Complete solution to Go types: Complete list of constants and variables!

1. Type determined value

Typed values are explicitly bound to a specific data type. Type-determined values occupy a large part of Go, including but not limited to constants, variables, function return values, structure fields, etc. Here is an example of determining a value for a type:

The type-determined value is in the variable declaration

When you explicitly specify a type in a variable declaration, the variable is type-determined.

var x int = 10 // x is a type-determined value, type int
var y string = "Hello" // y is a type-determined value, type is string

The type-determined value is in the function return value

Functions can also return type-determined values.

func sum(a int, b int) int { // The return value type is clearly int
    return a + b
}

The type-determined value is in the structure field

Structure fields are also type-determined values.

type Person struct {
    Name string // Name is a type-determined value, type is string
    Age int // Age is a type-determined value, type int
}

Type-determined values in arrays and slices

The elements of arrays and slices are also type-determined values.

var arr [3]int = [3]int{1, 2, 3} // arr is a type-determined value, the type is [3]int
var s []string = []string{"a", "b", "c"} // s is a type-determined value, the type is []string

Type-determined values are in interfaces and type assertions

When you convert an interface value to a concrete type via a type assertion, the result is a type-determined value.

var i interface{} = "this is string"
str, ok := i.(string) // str is a type-determined value, type is string

Type-determined values are in type aliases and custom types

Even if you create a type alias or custom type, the type bound to the original type actually determines the value.

type Length int
var l Length = 10 // l is a type-determined value, the type is Length

These examples demonstrate how typed values permeate every aspect of the Go language, providing developers with strict type safety. When writing code, having a clear understanding of types can help you write more robust and safer programs.

2. Type of uncertain value

An untyped value is a value that has no explicit type. These values are not bound to any specific data type, so at compile time, the Go compiler infers their type based on context. Untyped values are a rather interesting and multi-faceted concept in Go. These values exist in constant declarations, arithmetic operations, and some built-in functions. Here’s an example of an untyped value:

Untyped values in arithmetic operations

When you perform an arithmetic operation using untyped values, the result is also an untyped value, unless there is a typed value in the operation, in which case the result will be a typed value.

const c = 3 // Undefined value
var d int = 2 // type determines value

// e is still an untyped value, because both values involved in the operation are untyped values.
const e = c * c

// f is a type-determined value because there is a type-determined value involved in the operation
var f = c * d

Untyped value in built-in function

Some Go built-in functions (such as len) return values of undefined type.

const s = "hello world"
const l = len(s) // l is an untyped value

Unspecified value and default type

Each untyped value has a default type associated with it, usually based on a literal or arithmetic expression.

const g = 42.0 //The default type is float64
const h = 'x' //The default type is rune

Undefined value in array length declaration

Untyped values can also be used in array length declarations.

const size = 4
var arr [size]int // Compiler infers size as int

Unspecified value and iota

iota is also an untyped value and is often used in enumerations.

const (
    zero = iota // zero is 0
    one // one is 1
)

Three Explicit Type Conversions and Type Inference

In Go language, type conversion and type inference are two very important concepts. Together they define how different types of values are handled at compile and run time. We will discuss both concepts in detail and illustrate their usage and importance with examples.

Explicit type conversion

Explicit type conversion is the operation of converting one data type to another data type explicitly through syntax.

Definition

In Go, the syntax for explicit type conversion is T(v), where T is the target type and v is the value to be converted.

var x float64 = 42.0
var y int = int(x) // Explicitly convert float64 to int

Restrictions and Restrictions

Explicit type conversion does not always work. The legality of the conversion depends on the source and target types. For example, you cannot directly convert a structure type to an integer or floating point number.

type myStruct struct {
    field int
}

var a myStruct
// var b int = int(a) // This is illegal

Type Inference

Type inference is the process by which the compiler automatically infers the type of a variable. In Go, this usually happens when using := for variable initialization.

Definition

When you declare a variable using the := operator without explicitly specifying a type, the Go compiler infers the variable’s type based on the type of the right-hand expression.

z := 42 // type inferred as int

Type inference in complex expressions

In complex expressions involving multiple types, Go will try its best to perform type inference to meet the type requirements of the expression.

var m float64 = 3.14
n := int(m) + 42 // int(m) explicit conversion, the result type is inferred to int

Type inference and type-indeterminate values

Type inference also works for untyped values. The compiler will infer the most appropriate type based on the context.

const p = 5 // value of uncertain type
var q = p // type inferred as int because p's default type is int

Four. Constants

In Go language, constants are immutable values, which are obviously different from variables. Once a constant is defined, its value cannot be changed. A constant can be an untyped value or a typed value.

Indeterminate type constant

Untyped constants are constants that have no explicit type. These constants are not bound to any specific data type, so at compile time, the Go compiler infers their type based on context.

const a = 42 // a is an untyped value because no type is explicitly specified

Type-determined constant

Typed constants are constants that are explicitly bound to a specific data type.

const c int = 42 // c is a typed value because its type is explicitly int

Auto-completion in constant declaration

In a constant declaration block, you can omit the type and value of subsequent constants and they will be automatically completed.

const (
    x int = 10
    y // y is also of type int, with a value of 10
)

Use iota in constant declaration

iota is a special constant generator, mainly used to create a set of increasing integer constants.

const (
    zero = iota // The value of zero is 0
    one // the value of one is 1
    two // the value of two is 2
)

Visibility and addressability of constants

A constant can be exported or non-exported, depending on whether its name begins with an uppercase letter. Constants are not addressable.

const ExportedConst = "I am visible" // Exportable constants
const unExportedConst = "I am not visible" // Unexportable constant

Constant overflow and default type

The value represented by an untyped constant may overflow its default type. In this case, compilation will only succeed if the constant is used in a context that can accommodate the value.

const big = 1 << 100 //The default type is int, but the value will overflow
var bigInt = big >> 99 // big is used in an int64 context, no overflow

String constant

A string constant is a sequence of characters enclosed in double quotes.

const hello = "Hello, world!"

Boolean constant

Boolean constants have only two possible values: true and false.

const flagTrue = true
const flagFalse = false

Enumeration constant

By using iota, you can create a set of increasing integer constants, typically used in enumerations.

type Weekday int

const (
    Sunday Weekday = iota
    Monday
    Tuesday
    // ...
    Saturday
)

Complex constant

Go supports complex types, and you can create complex constants.

const complexConst = 1 + 2i

Forced type conversion

You can convert a constant to another type by casting.

const integer = 42
const floatType = float32(integer)

Constant in calculation expression

A constant can also be the result of a evaluated expression, but the expression must contain only constant values.

const calculated = 3 * 2 // 6

Constant arrays and slices

Note that in Go, array size needs to be constant. But the size of slices and maps can change dynamically, so they cannot be constants.

const arraySize = 5
var arr [arraySize]int // legal

Five. Variables

Variables are storage units that store data values whose values can be changed at runtime. In the Go language, the use of variables is very flexible but has strict type safety.

Variable declaration and assignment

Basic Statement

Use the var keyword for variable declaration.

var x int

Declaration and assignment at the same time

var y int = 42

Or use the short variable declaration form:

z := 42

Multi-variable declaration

var a, b, c int

or

var (
    d int
    e float64
)

Type Description

Basic type

Includes int, float64, bool, < strong>string etc.

var integerVar int = 10
var floatVar float64 = 10.99
var boolVar bool = true
var stringVar string = "Hello, Go"

numeric type

Go supports multiple numeric types, including int8, int16, int32, int64, uint8, uint16< /strong>, uint32, uint64, float32 >, float64 etc.

var smallInt int8 = 127
var largeInt int64 = 9223372036854775807
var unsignedInt uint16 = 65535
var floatNum float32 = 3.141592

Characters and strings

Go has rune and byte types to represent Unicode characters and ASCII characters.

var asciiChar byte = 'A'
var unicodeChar rune = 'you'
var str string = "Hello, World!"

Boolean type

The Boolean type has only two values: true and false.

var isActive bool = true
var isCompleted bool = false

Pointer

Go supports pointer types, but not pointer arithmetic.

var pointer *int
x := 42
pointer = &x

Arrays and slices

var arrayExample [5]int = [5]int{1, 2, 3, 4, 5}
var sliceExample[]int = arrayExample[1:4]

Mapping (Maps)

var countryCapitalMap map[string]string
countryCapitalMap = make(map[string]string)
countryCapitalMap["France"] = "Paris"

Structs

type Employee struct {
    ID int
    Name string
    Salary float64
}

var emp Employee

Interfaces

type Shape interface {
    Area() float64
}

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return 3.14159 * c.Radius * c.Radius
}

var s Shape = Circle{5.0}

Function type

In Go, functions are also types and can be passed as parameters.

type AddFunc func(a int, b int) int

var add AddFunc = func(a int, b int) int {
    return a + b
}

Channels

var messageChannel chan string = make(chan string)

Composite type

Examples include arrays, slices, maps, channels, structures, and interfaces.

array

var arr [5]int

slice

var slice []int

Mapping

var mapping map[string]int

channel

var ch chan int

structure

type Person struct {
    name string
    age int
}

var p Person

Interface

type Geometry interface {
    Area() float64
}

var g Geometry

Addressability of value

Some variables in Go language are addressable, which means you can get the memory address of this variable.

var myVar int = 42
var p *int = &myVar

Variable scope

In Go, variables can have different scopes: global scope, package scope, function scope, code block scope, etc.

var globalVar int // global scope

func myFunction() {
    var functionVar int // function scope
    {
        var blockVar int // code block scope
    }
}

Seven. Advanced usage of constants and variables

In Go programming, constants and variables are more than simple ways of storing data. They have various advanced uses to optimize code, increase efficiency, or implement complex programming patterns.

Advanced usage of constants

Enumeration and iota

Go supports the implementation of enumeration types through the iota keyword. This is very useful in a group of constant declarations.

const (
    Monday = iota + 1 // Monday = 1
    Tuesday // Tuesday = 2
    Wednesday // Wednesday = 3
)

Type alias

Using type aliases, you can restrict constants to custom types.

type Weekday int

const (
    Sunday Weekday = iota
    Monday
    // ...
)

Untyped and typed constants

Untyped constants can be used in a variety of situations, and their type will be inferred based on the context.

const x = 42 // untyped constant
var i int = x
var f float64 = x

Advanced usage of variables

Variable scope

Go supports block-level scoping. You can control the visibility of variables by declaring variables at different levels (global, package level, function level, etc.) through the var keyword.

var globalVar = 42 // global variable

func main() {
    var funcVar = "I'm local" // Function level variable
}

Lazy initialization

Using the init() function, you can initialize variables before the program starts execution.

var complexVar complex128

func init() {
    complexVar = cmplx.Sqrt(-5 + 12i)
}

Pointer and address operators

Although the Go language does not provide pointer arithmetic, it allows you to use the address operator & amp; and the dereference operator * to operate pointers.

x := 42
p := &x
fmt.Println(*p) // Output 42

Use tags and structures

Within a struct, you can use tags to attach metadata, which is useful during serialization and deserialization.

type Person struct {
    Name string `json:"name"`
    Age int `json:"age"`
}

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 4383 people are learning the system

syntaxbug.com © 2021 All Rights Reserved.