厚土Go学习笔记 | 07. 基本类型

时间:2022-05-06
本文章向大家介绍厚土Go学习笔记 | 07. 基本类型,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Go语言的基本类型有

bool string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr byte //uint8的别名 rune //uint32的别名,代表一个unicode码 float32 float64 complex64 complex128

这些类型中 int uint uintptr根据运行的系统不同,在32位的系统上是32位的,在64位的系统上是64位的。

当你需要使用一个整数类型时,你应该首选 int,仅当有特别的理由才使用定长整数类型或者无符号整数类型。

变量语法块

var (
    Tobe    bool    =   false
    Maxint  uint64  =   1<<64 - 1
    z   complex128  =   cmplx.Sqrt(-5 + 12i)
)

仔细比较完整代码中 PrintlnPrintf 的不同。

package main

import (
    "fmt"
    "math/cmplx"
)

var (
    Tobe    bool    =   false
    Maxint  uint64  =   1<<64 - 1
    z   complex128  =   cmplx.Sqrt(-5 + 12i)
)

func main() {
    const f = "%T(%v)n"
    fmt.Println(f, Tobe, Tobe)
    fmt.Println(f, Maxint, Maxint)
    fmt.Println(f, z, z)
    fmt.Printf(f, Tobe, Tobe)
    fmt.Printf(f, Maxint, Maxint)
    fmt.Printf(f, z, z)
}

运行结果

%T(%v)
 false false
%T(%v)
 18446744073709551615 18446744073709551615
%T(%v)
 (2+3i) (2+3i)
bool(false)
uint64(18446744073709551615)
complex128((2+3i))

很明显,Println只是输出了字符串或者变量值,Printf在输出变量的时候对变量进行了格式化。