Table of Contents
Basic data type description
Integer type
Character
Discussion on the essence of character type
Pointer
值类型与引用类型
基本数据类型默认值
Home Backend Development Golang What data types are there in go language?

What data types are there in go language?

Jun 07, 2021 pm 02:34 PM
go language type of data

The data types of go language are: 1. Boolean type; 2. Numeric type (can be divided into integer and floating point types); 3. String type; 4. Pointer type; 5. Array type; 6. Structured type; 7. Channel type; 8. Function type; 9. Slice type; 10. Interface type; 11. Map type.

What data types are there in go language?

The operating environment of this tutorial: Windows 10 system, GO 1.11.2, Dell G3 computer.

Go language is a statically typed programming language. In Go programming language, data types are used to declare functions and variables. The emergence of data types is to divide data into data with different memory sizes required. When programming, you need to apply for large memory only when you need to use big data, so that you can make full use of the memory. When the compiler compiles, it must know the type of each value, so that the compiler knows how much memory to allocate for this value, and what this allocated memory represents.

Basic data type description

##uint32-bit or 64-bituint8Unsigned 8 Bit integer type (0 to 255)uint16Unsigned 16-bit integer type (0 to 65535) uint32Unsigned 32-bit integer type (0 to 4294967295)uint64Unsigned 64-bit integer type (0 to 18446744073709551615)int32-bit or 64-bit int8Signed 8-bit integer (-128 to 127)int16Signed 16-bit integer (-32768 to 32767)int32Signed 32-bit integer (-2147483648 to 2147483647)int64Signed 64-bit integer (-9223372036854775808 to 9223372036854775807)byteuint8 alias (type byte = uint8) runeint32 alias (type rune = int32), represents a unicode code uintptr unsigned integer type, used to store a pointer is an unsigned integer type, no specific bit is specified size but large enough to accommodate pointers. float32IEEE-754 32-bit floating point number##float64complex64complex128

Integer type

Integer data is divided into two categories, signed and unsignedtwo types

Signed: int, int8, int16, int32, int64

Unsigned: uint, uint8, uint16, uint32, uint64, byte
Different bits The difference between the integer types of numbers is that they can store the size of the integer range;

The signed type can store any integer, and the unsigned type can only store natural numbers

The size of int and uint depends on the system , 32-bit system represents int32 and uint32, if it is a 64-bit system, it represents int64 and uint64

byte is similar to uint8, and is generally used to store a single character

To ensure that the program runs correctly, try to Use data types that occupy small space

fmt.Printf("%T", var_name) output variable type

unsafe.Sizeof(var_name) view the bytes occupied by variables

Floating point type

The floating point type is the decimal type and can store decimals. For example, 6.6, -12.34

1. A brief explanation of the storage form of floating point numbers in the machine. Floating point numbers = sign bit, exponent bit, mantissa bit

2. The mantissa part may be lost, resulting in loss of accuracy. . -123.0000901

package main

import "fmt"

func main() {
    
    var num1 float32 = -123.0000901
    var num2 float64 = -123.0000901
    fmt.Println("num1 = ", num1, "num2 = ", num2);
}
Copy after login

Note: The precision of float64 is more accurate than float32

Note: If we want to save a high-precision number, we should choose float64

3. The storage of floating point type is divided into three parts: sign bit, exponent bit, mantissa bit. During the storage process, the accuracy will be lost

4. The default floating point type of golang is float64 type

5. Under normal circumstances, float64 should be used because it is more accurate than float32

6. 0.123 can be abbreviated as .123, and it also supports scientific notation: 5.1234e2 is equivalent In 512.34

Character

There is no special character type in Golang. If you want to store a single character (letter), byte is generally used to save it.

A string is a sequence of characters connected by a fixed length of characters. Go's strings are connected by single bytes, which means that traditional strings are composed of characters, but Go's strings are different, they are composed of bytes.

  • Characters can only be wrapped in single quotes, not double quotes. Double quotes wrap strings
  • When we directly output the type value, the ASCII code of the corresponding character is output. Value
  • When we want to output the corresponding characters, we need to use formatted output
  • Go language characters use UTF-8 encoding, English letters occupy one character, and Chinese characters occupy three characters
  • In Go, the essence of a character is an integer. When output directly, it is the UTF-8 encoding code value corresponding to the character.
  • You can directly assign a number to a variable, and then when formatting the output %c will output the unicode character corresponding to the number
  • The character type can be calculated and is equivalent to an integer , because they all have corresponding unicode codes
package main

import "fmt"

func main() {
    
    //字符只能被单引号包裹,不能用双引号,双引号包裹的是字符串
    var c1 byte = 'a'
    var c2 byte = '0'

    //当我们直接输出type值时,就是输出了对应字符的ASCII码值
    //'a' ==> 97
    fmt.Println(c1, "--", c2)
    //如果我们希望输出对应字符,需要使用格式化输出
    fmt.Printf("c2 = %c c2 = %c", c1, c2)
}
Copy after login

But if the characters we save are greater than 255, such as storing Chinese characters, the byte type cannot be saved. You can use uint or int type to save

Discussion on the essence of character type

  • Character type is stored in the computer, and the code value corresponding to the character needs to be stored (Integer) Find out

    Storage: Character--> Code value--> Binary--> Storage

    Read: Binary-->Code value--> Characters --> Read

  • The corresponding relationship between characters and code values ​​is determined by the character encoding table (it is specified)

  • ## The encoding of #Go language is unified into UTF-8. It is very convenient and unified, and there is no longer the problem of garbled encoding

Boolean type

The Boolean type is also called the bool type. The bool type data only allows the value true Or false

The bool type occupies 1 byte

The bool type is suitable for logical operations and is generally used for process control

String

The string is A sequence of concatenated characters of a fixed length. Go's strings are concatenated from single bytes. The bytes of strings in Go language use UTF-8 encoding to identify Unicode text

1. Once a string is assigned a value, it cannot be modified:

Strings are immutable in Go.

2. Two identification forms of strings

  • Double quotation marks will recognize escape characters

    var str = "abc\nabc" //输出时会换行
    Copy after login

  • Backticks, output in the native form of the string, including line breaks and special characters, can prevent attacks, output source code and other effects

    var str string = `abc\nabc` //输出时原样输出,不会转义
    Copy after login

3. String splicing method" "

var str string = "hello " + "world"
str += "!"
Copy after login

4. When one line of string is too long and you need to use multiple lines of string, you can use the following processing

//正确写法
str := "hello" + 
	" world!"
fmt.Println(str)

//错误写法
str := "hello "
	+ "world!"
fmt.Println(str)
Copy after login

Pointer

  • Basic data type, variables store values, also called value types

  • To get the address of a variable, use &, such as var num int, to get the address of num:&num

  • 指针类型,指针变量存的是一个地址,这个地址指向的空间存的才是值,比如:var ptr *int = &num

  • 获取指针类型所指向的值,使用:*,比如,var ptr *int,使用*ptr获取ptr指向的值

指针细节说明:

  • 值类型,都有对应的指针类型,形式为*数据类型,比如int对应的指针就是*int,float64对应的指针类型就是*float64,依此类推。

  • 值类型包括:基本数据类型数组结构体struct

值类型与引用类型

值类型和引用类型使用特点:

值类型:变量直接存储值,内存通常在中分配

引用类型:变量存储的是一个地址,这个地址对应的空间才真正存储数据(值),内存通常在上分配,当没有任何变量应用这个地址时,该地址对应的数据空间就成为一个垃圾,由GC来回收。

Golang中值类型和引用类型的区分

  • 值类型:基本数据类型(int系列、float系列、bool、string)、数组和结构体

  • 引用类型:指针、slice切片、map、管道chan、interface等都是引用类型

基本数据类型默认值

在Golang中,数据类型都有一个默认值,当程序员没有赋值时,就会保留默认值,在Golang中,默认值也叫做零值。

基本数据类型默认值如下:

Type Description
The uintptr type is only needed in low-level programming, especially where Go language interacts with C language function library or operating system interface.
IEEE-754 64-bit floating point number
32-bit real and imaginary number
64 Real and imaginary numbers
数据类型默认值
整型0
浮点型0
字符串""
布尔类型false
package main

import "fmt"

func main() {
    
    var a int
    var b float32
    var isTrue bool
    var str string

    //这里的%v,表示按照变量的值输出
    fmt.Printf("a = %v, b = %v, isTrue = %v, str = %v", a, b, isTrue, str)
    fmt.Println("")
}
Copy after login

推荐学习:Golang教程

The above is the detailed content of What data types are there in go language?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use reflection to access private fields and methods in golang How to use reflection to access private fields and methods in golang May 03, 2024 pm 12:15 PM

You can use reflection to access private fields and methods in Go language: To access private fields: obtain the reflection value of the value through reflect.ValueOf(), then use FieldByName() to obtain the reflection value of the field, and call the String() method to print the value of the field . Call a private method: also obtain the reflection value of the value through reflect.ValueOf(), then use MethodByName() to obtain the reflection value of the method, and finally call the Call() method to execute the method. Practical case: Modify private field values ​​and call private methods through reflection to achieve object control and unit test coverage.

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

The difference between performance testing and unit testing in Go language The difference between performance testing and unit testing in Go language May 08, 2024 pm 03:09 PM

Performance tests evaluate an application's performance under different loads, while unit tests verify the correctness of a single unit of code. Performance testing focuses on measuring response time and throughput, while unit testing focuses on function output and code coverage. Performance tests simulate real-world environments with high load and concurrency, while unit tests run under low load and serial conditions. The goal of performance testing is to identify performance bottlenecks and optimize the application, while the goal of unit testing is to ensure code correctness and robustness.

What pitfalls should we pay attention to when designing distributed systems with Golang technology? What pitfalls should we pay attention to when designing distributed systems with Golang technology? May 07, 2024 pm 12:39 PM

Pitfalls in Go Language When Designing Distributed Systems Go is a popular language used for developing distributed systems. However, there are some pitfalls to be aware of when using Go, which can undermine the robustness, performance, and correctness of your system. This article will explore some common pitfalls and provide practical examples on how to avoid them. 1. Overuse of concurrency Go is a concurrency language that encourages developers to use goroutines to increase parallelism. However, excessive use of concurrency can lead to system instability because too many goroutines compete for resources and cause context switching overhead. Practical case: Excessive use of concurrency leads to service response delays and resource competition, which manifests as high CPU utilization and high garbage collection overhead.

Golang technology libraries and tools used in machine learning Golang technology libraries and tools used in machine learning May 08, 2024 pm 09:42 PM

Libraries and tools for machine learning in the Go language include: TensorFlow: a popular machine learning library that provides tools for building, training, and deploying models. GoLearn: A series of classification, regression and clustering algorithms. Gonum: A scientific computing library that provides matrix operations and linear algebra functions.

The role of Golang technology in mobile IoT development The role of Golang technology in mobile IoT development May 09, 2024 pm 03:51 PM

With its high concurrency, efficiency and cross-platform nature, Go language has become an ideal choice for mobile Internet of Things (IoT) application development. Go's concurrency model achieves a high degree of concurrency through goroutines (lightweight coroutines), which is suitable for handling a large number of IoT devices connected at the same time. Go's low resource consumption helps run applications efficiently on mobile devices with limited computing and storage. Additionally, Go’s cross-platform support enables IoT applications to be easily deployed on a variety of mobile devices. The practical case demonstrates using Go to build a BLE temperature sensor application, communicating with the sensor through BLE and processing incoming data to read and display temperature readings.

The evolution of golang function naming convention The evolution of golang function naming convention May 01, 2024 pm 03:24 PM

The evolution of Golang function naming convention is as follows: Early stage (Go1.0): There is no formal convention and camel naming is used. Underscore convention (Go1.5): Exported functions start with a capital letter and are prefixed with an underscore. Factory function convention (Go1.13): Functions that create new objects are represented by the "New" prefix.

Can golang variable parameters be used for function return values? Can golang variable parameters be used for function return values? Apr 29, 2024 am 11:33 AM

In Go language, variable parameters cannot be used as function return values ​​because the return value of the function must be of a fixed type. Variadics are of unspecified type and therefore cannot be used as return values.

See all articles