golang基础

本文深入探讨Go语言中的变量、函数、闭包、内存管理和并发特性。通过实例解析了++/--操作符的使用限制,函数参数入栈顺序,以及defer语句与返回值的关系。此外,介绍了逃逸分析在内存管理中的作用,并展示了如何利用make创建切片、地图和通道。文章还讨论了Go语言中的匿名和具名返回值,并分析了defer中函数参数值的取用时机。
摘要由CSDN通过智能技术生成
  • ++/-- 是语句,不是表达式,只能单独成句
var n = 0
// 错误使用
// func add() int {
//     n = n++		// syntax error: unexpected ++ at end of statement
// 	   return n++	// syntax error: unexpected ++ at end of statement
// }

func add() int {
	n++	// 单独成句
	return n
}
  • 函数参数入栈顺序:从右往左??
package main

import "fmt"

var cnt = 1

func f1() int {
    cnt++
    return cnt
}

func f2() int {
    cnt--
    return cnt
}

func main() {
	fmt.Println(f1(), f2()) // 2 1???为什么不是先执行f2()
}
  • 闭包 = 函数 + 运行环境
func makeSuffixFunc(suffix string) func(string) string {
	return func(name string) string {
		if !strings.HasSuffix(name, suffix) {
			return name + suffix
		}
		return name
	}
}

func main() {
	jpgFunc := makeSuffixFunc(".jpg")
	txtFunc := makeSuffixFunc(".txt")
	fmt.Println(jpgFunc("test")) //test.jpg
	fmt.Println(txtFunc("test")) //test.txt
}
  • 查看go内置函数定义:go doc builtin.make
package builtin // import "builtin"

func make(t Type, size ...IntegerType) Type
    The make built-in function allocates and initializes an object of type
    slice, map, or chan (only). Like new, the first argument is a type, not a
    value. Unlike new, make's return type is the same as the type of its
    argument, not a pointer to it. The specification of the result depends on
    the type:

        Slice: The size specifies the length. The capacity of the slice is
        equal to its length. A second integer argument may be provided to
        specify a different capacity; it must be no smaller than the
        length. For example, make([]int, 0, 10) allocates an underlying array
        of size 10 and returns a slice of length 0 and capacity 10 that is
        backed by this underlying array.
        Map: An empty map is allocated with enough space to hold the
        specified number of elements. The size may be omitted, in which case
        a small starting size is allocated.
        Channel: The channel's buffer is initialized with the specified
        buffer capacity. If zero, or the size is omitted, the channel is
        unbuffered.
  1. 匿名返回值:返回值为局部变量的副本
func f1() int {
	x := 5
	defer func() {
		x++
	}()
	return x
}

func main() {
	fmt.Println(f1())	// 输出5,返回值为x的副本,defer修改x不修改返回值
}
  1. 具名返回值:局部变量共享返回值
func f1() (x int) {
	defer func() {
		x++
	}()
	return 5
}

func main() {
	fmt.Println(f1())	// 输出6,defer中修改的x为返回值
}
  1. defer中函数参数值取用在调用defer语句时的值,而非执行defer语句时
func main() {
	a := 1
	defer func(x int) {
		fmt.Println(x)	// 1
	}(a)
	a++
	fmt.Println(a)		// 2
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值