Go 1.22引入的包级变量初始化次序问题

本文永久链接 – https://tonybai.com/2024/03/29/the-issue-in-pkg-level-var-init-order-in-go-1-22 细心的朋友可能已经注意到,从春节后,我的博客就“停更”了!实际上,这一情况部分是因为工作上的事务繁忙,另一部分则是因为我将工作之外的闲暇时间更多地投入到一本即将于今年中下旬出版的书的撰写了:在之前的积累基础上,我花了两个多月的时间完成了初稿。 ...

March 29, 2024 · 7 min · Tony Bai

Go 1.21中值得关注的几个变化

本文永久链接 – https://tonybai.com/2023/08/20/some-changes-in-go-1-21 美国时间2023年8月8日,Go团队在Go官博上正式发布了1.21版本! 早在今年4月末,我就撰写了文章《Go 1.21新特性前瞻》,对Go 1.21可能引入的新特性、新优化和新标准库包做了粗略梳理。 ...

August 20, 2023 · 26 min · Tony Bai

len(s)表达式的求值结果究竟是常量还是变量?我来告诉你

本文永久链接 – https://tonybai.com/2022/03/24/the-result-of-a-len-expression-is-constant-or-variable len是Go预定义标识符,同时也是Go内置的预定义函数,通过go doc工具我们能查到len函数的doc如下: $go doc builtin.len package builtin // import "builtin" func len(v Type) int The len built-in function returns the length of v, according to its type: Array: the number of elements in v. Pointer to array: the number of elements in *v (even if v is nil). Slice, or map: the number of elements in v; if v is nil, len(v) is zero. String: the number of bytes in v. Channel: the number of elements queued (unread) in the channel buffer; if v is nil, len(v) is zero. For some arguments, such as a string literal or a simple array expression, the result can be a constant. See the Go language specification's "Length and capacity" section for details. 对于len函数,即便是Go初学者也不会陌生,因为在日常Go开发中,len是一个高频使用的函数。len的参数主要是复合数据类型的变量,比如数组(包括执行数组的指针类型)、切片、字符串、channel等,返回的结果是这些复合数据变量的长度(length),是一个int类型的值。太多细节我就不说了,大家可能也都很熟悉。我要说的是,关于len函数的一个大家可能不熟悉的或不太在意的地方,那就是len(s)表达式在什么时候的求值结果为一个常量(constant),什么时候的求值结果为变量。别忽视这个细节,这很可能让你的程序输出你意想不到的结果,下面我就来举例说明。 ...

March 24, 2022 · 7 min · Tony Bai