Title: Detailed explanation of data types in Go language
In Go language, data types are a very important concept. Go language provides rich data types, including basic data types, composite data types and custom data types. This article will introduce in detail the commonly used data types in the Go language and give specific code examples.
1. Basic data types
In Go language, integer data types include int, int8, int16, int32, int64 , uint, uint8, uint16, uint32, uint64, etc. Among them, the size of int depends on the word length of the current platform, while uint represents an unsigned integer type.
Sample code:
package main import "fmt" func main() { var a int = 10 var b uint = 20 fmt.Println(a, b) }
There are two types of floating point data types in Go language: float32 and float64, which represent single Precision floating point and double precision floating point.
Sample code:
package main import "fmt" func main() { var a float32 = 3.14 var b float64 = 6.28 fmt.Println(a, b) }
The character type in Go language is rune, which represents a Unicode character.
Sample code:
package main import "fmt" func main() { var ch rune = '中' fmt.Println(ch) }
The string type in Go language is string, which is expressed by double quotes or backticks.
Sample code:
package main import "fmt" func main() { var str1 string = "Hello, world!" var str2 string = `Go语言` fmt.Println(str1, str2) }
2. Composite data type
In Go language, arrays have a fixed length And the element type is the same data type.
Sample code:
package main import "fmt" func main() { var arr [5]int = [5]int{1, 2, 3, 4, 5} fmt.Println(arr) }
Slice is a dynamic array in the Go language with an unfixed length.
Sample code:
package main import "fmt" func main() { var slice []int = []int{1, 2, 3, 4, 5} fmt.Println(slice) }
Structure is a custom data type that can contain different types of fields.
Sample code:
package main import "fmt" type Person struct { Name string Age int } func main() { var p Person p.Name = "Alice" p.Age = 25 fmt.Println(p) }
Mapping is an unordered collection of key-value pairs.
Sample code:
package main import "fmt" func main() { var m map[string]int = map[string]int{ "a": 1, "b": 2, "c": 3, } fmt.Println(m) }
3. Custom data types
In Go language, you can use the type keyword to define custom data types.
Sample code:
package main import "fmt" type MyInt int func main() { var a MyInt = 10 fmt.Println(a) }
Summary:
This article introduces the commonly used data types in Go language, including basic data types, composite data types and custom data types, and Corresponding code examples are given. Familiarity with and understanding of various data types is the basis for learning and using Go language. I hope readers can better master the data types in Go language through this article.
The above is the detailed content of Detailed explanation of data types in Go language. For more information, please follow other related articles on the PHP Chinese website!