二进制的“魔术”:每个 Go 程序员都应掌握的位操作艺术
二进制的“魔术”:每个 Go 程序员都应掌握的位操作艺术 - Tony Bai Tony Bai 一个程序员的心路历程 Google Go语言编码风格规范 Google Go语言编码风格规范:指南篇 Google Go语言编码风格规范:决定篇 Google Go语言编码风格规范:最佳实践篇 Go语言第一课FAQ ...
二进制的“魔术”:每个 Go 程序员都应掌握的位操作艺术 - Tony Bai Tony Bai 一个程序员的心路历程 Google Go语言编码风格规范 Google Go语言编码风格规范:指南篇 Google Go语言编码风格规范:决定篇 Google Go语言编码风格规范:最佳实践篇 Go语言第一课FAQ ...
本文永久链接 – 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),什么时候的求值结果为变量。别忽视这个细节,这很可能让你的程序输出你意想不到的结果,下面我就来举例说明。 ...