指针
指针的概念
指针概念在Go语言中分为两个概念
类型指针,允许对这个指针类型的数据进行更改,传递数据使用指针,无需拷贝数据;和c/c++不同的是类型指针不能进行偏移和运算
切片,由指向起始元素的元素指针,元素数量和容量组成
Go语言中的指针相较简单,只需要知道指针地址,指针类型,指针取值几个概念即可
指针地址与指针类型
每个变量在运行时都拥有一个内存地址,Go语言中使用”&”放在变量前,去取变量的内存地址。
- 示例:
1 | package main |
获取指针指向的值
在变量使用“&”获取内存地址后,可以使用”*”获取指针地址/指针变量指向的值
示例:
1 | package main |
使用指针修改值
- 示例:
1 | package main |
创建指针的另一种方法
- 格式:
1 | new(Type) |
- 示例:
1 | package main |
常量
相对于变量,常量就是恒定不变的量,例如圆周率,一周几天;常量的声明和变量的声明非常类似,只是把var换成const
1 | const pi = 3.1415926 |
常量的枚举
Go语言的枚举是要常量配合iota模拟,常量的作用:如果在编码过程中如果常量的值特别多,很容易重复或者写错,使用iota自动生成就很方便了
1 | package main |
将枚举值转换成字符串
- 使用String()方法的Week在使用上和普通常量上没有区别,当这个类型需要显示为字符串时,Go语言会自动找String()方法并进行调用
1 | package main |
类型别名
类型别名与类型定义
- 定义区别
1 | type newInt int // 类型定义 |
- 示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20package main
import "fmt"
type newInt int
type aliasInt = int
func main() {
var (
a newInt
b aliasInt
)
fmt.Printf("a的类型:%T\nb的类型:%T\n", a, b)
}
//输出:
go run "./类型别名类型定义区别.go"
a的类型:main.newInt
b的类型:int
非本地类型不能定义方法
- 一般类型别名不能定义方法,类型定义可以定义方法,类型别名如果想要定义方法,类型别名定义必须定义在原类型所在的包中
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2019/12/10/Go语言复习笔记——基本语法二之常量指针与类型别名/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!