数据类型指定有效的Go变量可以保存的数据类型。在Go语言中,类型分为以下四类:
- 基本类型:数字,字符串和布尔值属于此类别。
- 聚集类型:数组和结构属于此类别。
- 引用类型:指针,切片,地图,函数和通道属于此类别。
- 接口类型
在这里,我们将讨论Go语言中的Basic Data Types。在基本数据类型被进一步划分为三个子类别分别是:
- 数字
- 布尔值
- 弦乐
数字
在Go语言中,数字分为三个子类别:
- Int:在Go语言中,有符号和无符号整数都可以使用四种不同的大小,如下表所示。有符号的int由int表示,而无符号的整数由uint表示。
数据类型
描述
例:
// Go program to illustrate
// the use of integers
package main
import "fmt"
func main() {
// Using 8-bit unsigned int var X uint8 = 225 fmt.Println(X+1, X)
// Using 16-bit signed int
var Y int16 = 32767
fmt.Println(Y+2, Y-2)
}
输出:
226 225
-32767 32765
浮点数:在围棋语言,浮点数被分成*2类如示于下表:
例:
// Go program to illustrate
// the use of floating-point
// numbers
package main
import "fmt"
func main() { a := 20.45 b := 34.89
// Subtraction of two // floating-point number c := b-a
// Display the result fmt.Printf("Result is: %f", c)
// Display the type of c variable
fmt.Printf("\nThe type of c is : %T", c)
}
输出:
结果是:14.440000 c的类型是:float64
*复数:下表将复数分为两部分。float32和float64也是这些复数的一部分。内置函数根据其虚部和实部创建复数,而内置虚部和实函数则提取那些虚部。
例:
// Go program to illustrate // the use of complex numbers package main import "fmt" func main() { var a complex128 = complex(6, 2) var b complex64 = complex(9, 2) fmt.Println(a) fmt.Println(b) // Display the type fmt.Printf("The type of a is %T and "+ "the type of b is %T", a, b) }
输出:
``` (6 + 2i) (9 + 2i) a的类型为complex128,b的类型为complex64 ```
布尔值
布尔数据类型仅代表真或假信息的一位。布尔类型的值不会隐式或显式转换为任何其他类型。
例:
// Go program to illustrate // the use of booleans package main import "fmt" func main() { // variables str1 := "GeeksforGeeks" str2:= "geeksForgeeks" str3:= "GeeksforGeeks" result1:= str1 == str2 result2:= str1 == str3 // Display the result fmt.Println( result1) fmt.Println( result2) // Display the type of // result1 and result2 fmt.Printf("The type of result1 is %T and "+ "the type of result2 is %T", result1, result2) }
输出:
false true result1的类型为bool,result2的类型为bool
fmt
字符串数据类型表示Unicode代码点的序列。换句话说,我们可以说一个字符串是不可变字节的序列,这意味着一旦创建了一个字符串,您就无法更改该字符串。字符串可以包含任意数据,包括以人类可读形式包含零值的字节。
例:
// Go program to illustrate // the use of strings package main import "fmt" func main() { // str variable which stores strings str := "GeeksforGeeks" // Display the length of the string fmt.Printf("Length of the string is:%d", len(str)) // Display the string fmt.Printf("\nString is: %s", str) // Display the type of str variable fmt.Printf("\nType of str is: %T", str) }
输出:
字符串的长度是:13 字符串是:GeeksforGeeks str的类型是:string
© 著作权归作者所有
发表评论