Go 基础篇教程-变量

栏目: Go · 发布时间: 6年前

内容简介:二、变量定义四种变量定义类型:

一、 Go 内建变量类型

bool
string
(u)int、(u)int8、(u)int16、(u)int32、(u)int64
uintptr 指针
byte
rune 字符型,32 位,类比 char
float32、float64
complex32、complex64 复数

类型转换 type(varName)

func typeConversion () {
    var int a = 5
    var b = "str"
    c := 3
    var int d
    d = int(a / c) 
    fmt.Println(d, b)
}

二、变量定义四种变量定义类型:

第一种完全体:var name type = value
第二种简单体:var name = value //name根据value的类型自动识别类型
第三种最简体:name := value //只适用于函数体内,name根据value的类型自动识别类型
第四种包内聚合定义: var (name1 = value1 name2 = value2 ...)

变量定义

func definedVariable() {
    var a int = 5
    var b = "str"
    c, d := 3, "string"
    var e int   //整型默认初始值为0
    var f string //字符串默认初始值为""
    var g bool  //bool默认初始值为false
}
//包内变量
var {
    name1 = 100
    name2 = "abc"
    ...
}

三、变量和枚举类型两种常量定义:常量定义必须赋值

第一种完全体:const name type = value 
第二种简单体:const name = value //name根据value的类型自动识别类型

定义常量

func definedConst () {
    const fileName string = "readme.txt"
    const a, b = 12, 5
    var c int
    c = int(math.Sqrt(a*a + b*b)) // 由于类型不定,所以这里不需要强转,如果定义为 const a, b int = 3, 4,则需要强转
    fmt.Println(fileName, a, b, c)
}

枚举类型: 在Go语言中没有枚举类型,使用const来代替

自定义
const(
name1 = value1
name2 = value2
 ...
)
iota 实现枚举自增
iota 表达式枚举:const ( name1=iota表达式 name2 )

定义枚举

func dedinedEnmu () {
    const (
        doctor_type = 0
        nurse_type = 1
        pharmacist_type = 2
    )
fmt.Println(dcotor_type, nurse_type, pharmacist_type) // 0,1,2

const (
        doctor_type = iota
        nurse_type
        pharmacist_type 
    )
fmt.Println(dcotor_type, nurse_type, pharmacist_type) // 0,1,2
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Effective Python

Effective Python

布雷特·斯拉特金(Brett Slatkin) / 爱飞翔 / 机械工业出版社 / 2016-1 / 59

用Python编写程序,是相当容易的,所以这门语言非常流行。但若想掌握Python所特有的优势、魅力和表达能力,则相当困难,而且语言中还有很多隐藏的陷阱,容易令开发者犯错。 本书可以帮你掌握真正的Pythonic编程方式,令你能够完全发挥出Python语言的强大功能,并写出健壮而高效的代码。Scott Meyers在畅销书《Effective C++》中开创了一种以使用场景为主导的精练教学方......一起来看看 《Effective Python》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具