search
HomeBackend DevelopmentGolangWhat data types are there in go language?

What data types are there in go language?

Jun 07, 2021 pm 02:34 PM
go languagetype 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);
}

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)
}

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" //输出时会换行

  • 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` //输出时原样输出,不会转义

3. String splicing method" "

var str string = "hello " + "world"
str += "!"

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)

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("")
}

推荐学习: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
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
How to do the security settings of LibOffice on DebianHow to do the security settings of LibOffice on DebianMay 16, 2025 pm 01:24 PM

Ensuring overall security on Debian systems is crucial to protecting the running environment of applications such as LibOffice. Here are some general recommendations for improving system security: System updates regularly update the system to patch known security vulnerabilities. Debian12.10 released security updates that fixed a large number of security vulnerabilities, including some critical software packages. User permission management avoids the use of root users for daily operations to reduce potential security risks. It is recommended to create a normal user and join the sudo group to limit direct access to the system. The SSH service security configuration uses SSH key pairs to authenticate, disable root remote login, and restrict login with empty passwords. These measures can enhance the security of SSH services and prevent

How to configure Rust compilation options on DebianHow to configure Rust compilation options on DebianMay 16, 2025 pm 01:21 PM

Adjusting Rust compilation options on Debian system can be achieved through various ways. The following is a detailed description of several methods: Use the rustup tool to configure and install rustup: If you have not installed rustup yet, you can use the following command to install: curl--proto'=https'--tlsv1.2-sSfhttps://sh.rustup.rs|sh Follow the prompts to complete the installation process. Set compilation options: rustup can be used to configure compilation options for different toolchains and targets. You can set compilation options for a specific project using the rustupoverride command. For example, if you want to set a specific Rust version for a project

How to manage Kubernetes nodes on DebianHow to manage Kubernetes nodes on DebianMay 16, 2025 pm 01:18 PM

Managing Kubernetes (K8S) nodes on a Debian system usually involves the following key steps: 1. Installing and configuring Kubernetes components preparation: Make sure that all nodes (including master nodes and worker nodes) have the Debian operating system installed and meet the basic requirements for installing a Kubernetes cluster, such as sufficient CPU, memory and disk space. Disable swap partition: In order to ensure that kubelet can run smoothly, it is recommended to disable swap partition. Set firewall rules: allow necessary ports, such as ports used by kubelet, kube-apiserver, kube-scheduler, etc. Install container

Golang's security settings on DebianGolang's security settings on DebianMay 16, 2025 pm 01:15 PM

When setting up a Golang environment on Debian, it is crucial to ensure system security. Here are some key security setup steps and suggestions to help you build a secure Golang development environment: Security setup steps System update: Make sure your system is up to date before installing Golang. Update the system package list and installed packages with the following command: sudoaptupdatesudoaptupgrade-y Firewall Configuration: Install and configure a firewall (such as iptables) to limit access to the system. Only necessary ports (such as HTTP, HTTPS, and SSH) are allowed. sudoaptininstalliptablessud

How to optimize the performance of Kubernetes deployment on DebianHow to optimize the performance of Kubernetes deployment on DebianMay 16, 2025 pm 01:12 PM

Optimizing and deploying Kubernetes cluster performance on Debian is a complex task involving multiple aspects. Here are some key optimization strategies and suggestions: Hardware resource optimization CPU: Ensure that sufficient CPU resources are allocated to Kubernetes nodes and pods. Memory: Increases the memory capacity of the node, especially for memory-intensive applications. Storage: Use high-performance SSD storage and avoid using network file systems (such as NFS) as they may introduce latency. Kernel parameter optimization edit /etc/sysctl.conf file, add or modify the following parameters: net.core.somaxconn: 65535net.ipv4.tcp_max_syn

How to schedule tasks in Debian by Python scriptsHow to schedule tasks in Debian by Python scriptsMay 16, 2025 pm 01:09 PM

In the Debian system, you can use cron to arrange timed tasks and realize the automated execution of Python scripts. First, start the terminal. Edit the crontab file of the current user by entering the following command: crontab-e If you need to edit the crontab file of other users with root permissions, please use: sudocrontab-uusername-e to replace username with the username you want to edit. In the crontab file, you can add timed tasks in the format as follows: *****/path/to/your/python-script.py These five asterisks represent minutes (0-59) and small

How to configure Golang network parameters in DebianHow to configure Golang network parameters in DebianMay 16, 2025 pm 01:06 PM

Adjusting Golang's network parameters in Debian system can be achieved in many ways. The following are several feasible methods: Method 1: Temporarily set environment variables by setting environment variables: Enter the following command in the terminal to temporarily set environment variables, and this setting is only valid in the current session. exportGODEBUG="gctrace=1netdns=go" where gctrace=1 will activate garbage collection tracking, and netdns=go will make Go use its own DNS resolver instead of the system default. Set environment variables permanently: add the above command to your shell configuration file, such as ~/.bashrc or ~/.profile

What are the shortcut keys for LibOffice on DebianWhat are the shortcut keys for LibOffice on DebianMay 16, 2025 pm 01:03 PM

The shortcut keys for customizing LibOffice on Debian systems can be adjusted through system settings. Here are some commonly used steps and methods to set LibOffice shortcut keys: Basic steps to set LibOffice shortcut keys Open system settings: In the Debian system, click the menu in the upper left corner (usually a gear icon), and select "System Settings". Select a device: In the system settings window, select "Device". Select a keyboard: On the Device Settings page, select Keyboard. Find the command to the corresponding tool: In the keyboard settings page, scroll down to the bottom to see the "Shortcut Keys" option. Clicking it will bring a window to a pop-up. Find the corresponding LibOffice worker in the pop-up window

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.