Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of Go data Type

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "Go data type case analysis". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Every variable has a data type, and the data types in Go are:

Simple data types: int, float, complex, bool and string

Data structures or combinations (composite): struct, array, slice, map and channel

Interface (interface)

When a variable is declared, it is initialized by default. The value of 0 initialized by default for each data type is different, for example, 0 of int type is numeric, 0 of float is 0, 0 of string type is empty "", 0 of bool type is false, 0 of data structure is 0 of nil,struct, and 0 of data structure is assigned 0 of all fields.

In fact, functions also have types, but they are generally called return types. For example, the return type of the following function foo is int:

Func foo () int {... CODE... Return INT_TYPE_VALUE}

The function allows multiple return values, separated by commas and surrounded by parentheses:

Func foo () (int,bool) Number type Integer

The Integer type is integer data, such as 322 01-3-22, and so on.

Integer in Go has the following types of subdivisions:

Int8,int16,int32,int64

Uint8,uint16,uint32,uint64

Byte

Rune

Int,uint

Where 8 16 32 64 represents the number of bit bits that can be stored by this data type. For example, int8 means that it can store 8-bit values, so this type takes up 1 byte, and it also means that the maximum number of integers that can be stored is 2 ^ 8 = 256. so the maximum positive number allowed for int8 type is 127. the minimum negative number allowed is-128. a total of 256 values.

The u in uint stands for unsigned, an unsigned integer that holds only 0 and positive numbers. So when uint8 can store 256 numbers, the minimum allowable value is 0 and the maximum allowable value is 255.

The two additional Integer are byte and rune, which are equivalent to uint8 (that is, a positive number of one byte) and int32, respectively. You can know from the definition in the builtin package:

$go doc builtin | grep-E "byte | rune" type byte = uint8type rune = int32

The byte type is explained in more detail later.

There are also two types that depend on the number of CPU bits, int and uint, which each represent a machine word length. On 32-bit CPU, a machine word length is 32bit, a total of 4 bytes, and on 64-bit CPU, a machine word length is 64bit, a total of 8 bytes. In addition to int and uint relying on the CPU architecture, there is another uintptr that also depends on machine word length.

In general, when you need to use integer data, you can specify int, and consider whether to replace it with other integer types when there is a clear additional need.

Adding a 0 prefix to an integer indicates that this is octal, for example, 077. Add the prefix 0x to indicate that this is hexadecimal, such as 0x0c, and use the e symbol to indicate that this is a scientific method of counting, such as 1e3 = 1000 line 6.023e23 = 6.023 x 10 ^ 23.

You can use TYPE (N) to generate a numeric value, such as a: = uint64 (5). This is actually type conversion, converting 5 of the int type to 5 of the int64 type.

Byte Typ

There is no special provision for character types in Go. All character types (whether ASCII characters or other multi-byte characters) within char,Go are saved with integer values, so characters can be stored in variables of data types such as byte, int, and so on. The byte type is equivalent to the uint8 type and represents an unsigned 1-byte integer.

Characters in Go are surrounded by single quotation marks, such as'a 'and' I', but it is wrong to contain multiple characters in single quotation marks (such as' aA') because the character type is one character.

For example, the letter an of ASCII stands for 97. The following definition is allowed:

Var a byte ='A' / / a=65var b uint8 ='a' / / baked 97

Note that characters must be in single quotation marks and must only be a single character. So the byte type is often called the character type.

The following are also allowed:

Var a = 'A'var a uint32 =' A'var an int64 ='A'

Therefore, the Integer type converts the character to the value corresponding to its binary value when it stores a character enclosed in single quotes. The same applies to unicode characters, which will be used to store the binary values corresponding to each byte:

Var an int64 ='I'/ / adept 25105

Because I occupy 3 bytes in Go, saving to byte reports an error:

Var a byte ='I'

You can save the code points of its unicode characters:

Var a byte ='\ u0041' / / aq65, the character A

If you don't know the value of the code point, you can save it as int and output it.

Fmt.Printf ("% d",'I') / / 25105

If you want to convert the byte value to characters, you can use the string () function to do a simple type conversion:

Var a = 'A'println (string (a)) / / output: Afloat and complex

Float is a floating point number (commonly known as decimal), such as 0.03.0-3.12-3.120, and so on.

There are two floating point types float in Go: float32 and float64.

Complex stands for plural types (imaginary numbers), with complex64 and complex128.

Floating-point numbers are very complex in computer systems, and for learning, you only need to think of them as a decimal in mathematics. But here are a few points to keep in mind:

Floating point numbers are imprecise. For example, 1.01-0.99 results in a mathematical value of 0.02, but the actual result is 0.0200000000000018 (the result of the python operation), which is represented as + 2.000000e-002 in Go. This result is a result that the limit approaches to our expected value.

The precision of float32 (7 decimal places) is lower than that of float64 (15 decimal places), so values of type float64 are more accurate than values of type float32.

Because floating-point numbers are not accurate, try not to compare two floating-point numbers with equivalents = = and non-equivalents! =, for example, (3.22.8) = 0.4 returns Flase. If you have to compare, you should find the absolute value by their subtraction, and compare it with a value that is small enough (will not affect the result), such as abs.

< 0.0002返回True。 一般来说,在程序中需要使用浮点数的时候都使用float64类型,不仅因为精确,更因为几乎所有包中需要float参数的类型都是float64。 在Go的数学运算中,默认取的是整型数据,如果想要得到浮点数结果,必须至少让运算的一方写成浮点数格式: var a := 3/2 // a得到截断的整数:a=1var b := 3/2.0 // b为浮点数b=+1.500000e+000var c := 3 + 2.0 // c为浮点数string类型 Go中的string用于保存UTF-8字符序列,它是动态大小的。对于字母和英文字母,它占用一个字节,对于其它unicode字符,按需占用2-4个字节。例如中文字符占用3个字节。 Go中的string类型要使用双引号或反引号包围,它们的区别是: 双引号是弱引用,其内可以使用反斜线转义符号,如ab\ncd表示ab后换行加cd 反引号是强引用,其内任何符号都被强制解释为字面意义,包括字面的换行。也就是所谓的裸字符串。 func main() { println("abc\ndef") println(`ABC DEF`)} 上面的结果将输出: abcdefABC DEF 不能使用单引号包围,单引号包围的表示它的二进制值转换成十进制的数值。例如字母对应的是ASCII码。这个在前面byte类型中介绍过。所以,使用单引号包围的字符实际上是整数数值。例如'a'等价于97。 string的底层是byte数组,每个string其实只占用两个机器字长:一个指针和一个长度。只不过这个指针在Go中完全不可见,所以对我们来说,string是一个底层byte数组的值类型而非指针类型。 所以,可以将一个string使用append()或copy()拷贝到一个给定的byte slice中,也可以使用slice的切片功能截取string中的片段。 func main() { var a = "Hello Gaoxiaofang" println(a[2:3]) // 输出:l s1 := make([]byte,30) copy(s1,a) // 将字符串保存到slice中 println(string(s1)) // 输出"Hello Gaoxiaofang"}字符串串接 使用加号+连接两段字符串:"Hello" + "World"等价于"HelloWorld"。 可以通过+的方式将多行连接起来。例如: str := "Beginning string "+ "second string" 字符串连接+操作符强制认为它两边的都是string类型,所以"abcd" + 2将报错。需要先将int类型的2转换为字符串类型(不能使用string(2)的方式转换,因为这种转换方式不能跨大类型转换,只能使用strconv包中的函数转换)。 另一种更高效的字符串串接方式是使用strings包中的Join()函数,它可以在缓冲中将字符串串接起来。 字符串长度 使用len()取字节数量(不是字符数量)。 例如len("abcde")返回5,size(我是中国人)返回15。 字符串截取 可以将字符串当作数组,使用索引号取部分字符串(按字节计算),索引号从0开始计算,如"abcd"[1]。 从字符串取字符的时候,需要注意的是index按字节计算而非按字符计算。两种取数据方式: "string"[x]"string"[x:y] 第一种方式将返回第(x+1)个字节对应字符的二进制数值,例如字母将转换为ASCII码,unicode将取对应字节的二进制转换为数值。 第二种方式将返回第(x+1)字节到第y字节中间的字符,Go中采取"左闭右开"的方式,所以所截取部分包括index=x,但不包括index=y。 例如: func main() { println("abcde"[1]) // (1).输出"98" println("我是中国人"[1]) // (2).输出"136" println("abcde"[0:2]) // (3).输出"ab" println("我是中国人"[0:3]) // (4).输出"我" println("abcde"[3:4]) // (5).输出"d"} 分析每一行语句: (1).取第2个字节的二进制值,即字符b对应的值,其ASCII为98 (2).取第2个字节的二进制值,因为中文占用3个字节,所以取第一个字符"我"的第二个字节部分,转换为二进制值,为136 (3).取第1个字节到第3个字节(不包括)中间的字符,所以输出"ab" (4).取前三个字节对应的字符,所以输出"我" (5).取第4个字节对应的字符,所以输出d 字符串遍历 字符串是字符数组,如果字符串中全是ASCII字符,直接遍历即可,但如果包含了多字节字符,则可以[]rune(str)转换后后再遍历。 package mainimport "fmt"func main() { str := "Hello 你好" r := []rune(str) // 8 for i := 0; i < len(r); i++ { fmt.Printf("%c", r[i]) }}字符串比较 可以使用< >

= =! = compare strings, which compare one character at a time. The letters are arranged in the ASCII form of A-Za-z.

/ / string comparison println ("a" < "B") / / false// numerical comparison, not string comparison println ('a'= = 97) / / true modifies the string

The string is an immutable object, so the way the string s is truncated and assigned to s [1] = "c" will report an error.

To modify the characters in a string, you must first copy the string into a byte slice, then modify the characters at the specified index position, and finally convert the byte slice back to the string type.

For example, change "gaoxiaofang" to "maoxiaofang":

S: = "gaoxiaofang" bs: = [] byte (s) bs [0] ='m'/ / you must use single quotation marks s = string (bs) println (s)

Note that when modifying a character, you must use single quotation marks because it is of type byte.

Boolean type (bool)

There are only two values for the bool type: true and false.

There are three Boolean logic operators: & & | |!, which are respectively logic and, logic or.

Func main () {println (true & & true) / / true println (true & & false) / / false println (true | | true) / / true println (true | | false) / / true println (! true) / / false}

Go is a very strict complaint, which requires that the data types on both sides must be the same when using = = for equivalence comparison, otherwise an error will be reported. If both data types are interface types, they must implement the same interface function. If it is a constant comparison, both sides must be compatible data types.

In the format of the function of the printf class, the placeholder% t is used to represent Boolean values.

Boolean variables and function names should start with is or Is to indicate that this is a Boolean thing. For example, the isSorted () function is used to detect whether the content has been sorted, and IsFinished () is used to determine whether it is complete.

Type keyword: type alias

You can use type to define your own data types, such as struct, interface.

You can also use type to define aliases for types. For example, define an alias of int type INT:

Type INT int

So the underlying data structure of the INT type is still the int type. You can use it like int:

Var an INT = 5

Multiple aliases can be declared at once in type:

Type (CT int IT int32 DT float32) gets the data type

TypeOf () of the reflect package, or "% T" of Printf/Sprintf.

Package mainimport ("reflect"fmt") type IT int32func main () {var an IT = 322 var b = 22 fmt.Println (reflect.TypeOf (a)) / / main.IT fmt.Println (reflect.TypeOf (b)) / / int fmt.Println (fmt.Sprintf ("% T", a)) / / main.IT} size of the data type

The Sizeof () of the unsafe package looks at the amount of space occupied by the data type to which the variable or constant belongs.

Package mainimport ("unsafe"fmt") type IT int32func main () {var an IT = 322 var b = 22 fmt.Println (unsafe.Sizeof (a)) / / 4 fmt.Println (unsafe.Sizeof (b)) / / 8} "Go data type instance analysis" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report