本文内容是本人对Go语言的变量、常量、数组、切片、映射、结构体的备忘录,记录了关键的相关知识点,以供翻查。
文中如有错误的地方请大家指出,以免误导!转摘本文也请注明出处,多谢!
参考书籍《Go语言圣经》、《Go语言实战》、《Go语言学习笔记》等
一、变量
var q int
var y = 453
var (
n,m = 134,"srf"
n1,m1 int
)
func f1() {
n,m := 25,"sss"
n,m1 := 34,"yyy"
fmt.Println(n,m,m1)
n = n+5 //赋值表达式中,首先计算右值
//“_”空标识符用来临时规避编译器对未使用变量和导入包的错误检查
if _,ok := add1(n);ok {
fmt.Println(n)
}
}
func add1(n int) (int, bool) {
return n+1,true
}
const i = 5
const (
x byte = 1
x1
x2 //x1,x2均为1
s = "abs"
s1 //s1=“abc”
)
const (
_,_ int = iota,iota*3 //0,0*3 忽略值,并显式指定类型为int
k1,k2 //1,1*3
l1,l2 //2,2*3
o1,o2 = 5,6 //中断iota自增
r1,r2 //5,6 同上一行
e1,e2 = iota,iota*3 //5,5*3 恢复iota自增,按行递增
)
//枚举
type color byte
const (
blue color = iota
red
green
)
func main() {
t:= blue
fmt.Println(t) //0
//fmt.Println(&i) //错误:无法对常量取地址 cannot take the address of i
}
三、数组
//切片本身是个只读对象,工作机制类似数组指针的一种包装
type slice struct{
array unsafe.Pointer
len int //可读写的元素数量
cap int //所引用数组片段的真实长度
}
//利用reslice实现一个栈式结构(也可将stack定义为一个类型)
var stack = make([]int,0,5)
func push(x int) error {
n:=len(stack)
if n == cap(stack) {
return errors.New("stack is full")
}
stack = stack[:n+1] //新的stack增加了一个可访问元素stack[n]
stack[n]=x
return nil
}
func pop() (int, error) {
n:=len(stack)
if n == 0 {
return 0,errors.New("stack is empty")
}
x:=stack[n-1]
stack = stack[:n-1] //新的stack减少了一个可访问元素stack[n-1]
return x,nil
}
func main() {
for i := 0; i < 7; i++ {
fmt.Printf("push %d: %v,%v\n",i,push(i),stack)
}
for i := 0; i < 7; i++ {
x,err:=pop()
fmt.Printf("push %d: %v,%v\n",x,err,stack)
}
}
m := users[int]user{
1:{"srf",25}
}
//m[1].age +=1 //错误,无法设置值
u := m[1]
u.age+=1
m[1] = u
func main() {
var lock sync.RWMutex
m:=make(map[string]int)
go func() {
for {
lock.Lock()
m["a"] += 1
lock.Unlock() //不能用defer
time.Sleep(time.Microsecond)
}
}()
go func() {
for {
lock.RLock()
_ = m["b"]
lock.RUnlock()
time.Sleep(time.Microsecond)
}
}()
select {} //阻止进程退出
}
func equal(x, y map[string]int) bool {
if len(x) != len(y) {
return false
}
for k, xv := range x {
if yv, ok := y[k]; !ok || yv != xv {
return false
}
}
return true
}
m:=make(map[string]bool)
if !m["srf"] {
m["srf"] = true
}
六、结构体
type node struct{
_ int
id int `账号`
next *node
}
u := struct{
name string
}
type file struct{
name string
attr struct{
owner int
perm int
}
}
f := file{name:"test.dat"}
f.attr.owner = 1
f.attr.perm = 0755
type user struct{
name string `昵称`
sex byte `性别`
}
func main(){
u:=user{"TOM",1}
v:=reflect.ValueOf(u)
t:=v.Type()
for i,n:=0,t.NumField();i<n;i++{
fmt.Printf("%s: %v\n", t.Field(i).Tag, v.Field(i))
}
}
原文:http://www.cnblogs.com/susufufu/p/7604480.html